qontain 0.0.0-stage → 0.1.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-APACHE 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 2026 Albin
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/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Albin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ qontain
2
+ Copyright 2026 Albin
3
+
4
+ This product is licensed under the MIT license (LICENSE-MIT) or the Apache
5
+ License, Version 2.0 (LICENSE-APACHE), at your option.
6
+
7
+ The logo's wordmark (docs/assets/logo-*.svg, social-preview.png) is drawn
8
+ from the Geist typeface, Copyright 2023 Vercel, in collaboration with
9
+ basement.studio, licensed under the SIL Open Font License, Version 1.1.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # qontain (TypeScript SDK)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ For agents running under the qontain runtime. No runtime dependencies; Node 22.18+.
4
+
5
+ ```sh
6
+ npm install qontain
7
+ ```
8
+
9
+ - `Broker`: calls brokered tools, sends messages on declared wires, and builds
10
+ egress URLs. Broker refusals reject with typed errors.
11
+ - `Agent`: HTTP server for the agent's ports, with `/health` built in and a
12
+ receiver for each wire channel.
13
+
14
+ ```ts
15
+ import { Agent, Broker, BudgetExceeded } from "qontain";
16
+
17
+ const broker = Broker.fromEnv(); // QONTAIN_BROKER, optional QONTAIN_BROKER_TOKEN
18
+
19
+ await new Agent("researcher", 8080)
20
+ .route("/research", async (body) => {
21
+ const { topic } = body as { topic: string };
22
+ try {
23
+ const hits = await broker.callTool("web-search", { q: topic });
24
+ await broker.send("findings", { topic, hits });
25
+ return { ok: true };
26
+ } catch (e) {
27
+ if (e instanceof BudgetExceeded) return { error: "tool budget used up" };
28
+ throw e;
29
+ }
30
+ })
31
+ .channel("reviews", (message, sourceAgent) => ({ ack: true }))
32
+ .listen();
33
+ ```
34
+
35
+ LLM SDKs need no changes: qontain sets `ANTHROPIC_BASE_URL` and
36
+ `OPENAI_BASE_URL` to the broker. For other APIs use
37
+ `broker.egressUrl("api.example.com", "v1/items")`.
38
+
39
+ Errors: `BrokerAuthError` (401), `PolicyDenied` (403), `ReplayDivergence`
40
+ (409, strict replay has no recorded response to this request; `detail.differed`
41
+ says why), `ReplayExhausted` (410), `SchemaViolation` (422, `detail` has the reason), `BudgetExceeded` (429),
42
+ `ToolUnavailable` (501), `UpstreamError` (502), `BrokerUnavailable` (503). All
43
+ extend `BrokerDenied` (`isDenial` is true) and `BrokerError`, which is also
44
+ thrown as-is for error statuses that did not come from broker policy.
45
+ `BrokerTransportError` (`status` is undefined, the original error is `cause`)
46
+ means the broker could not be reached or did not answer within `timeoutMs`;
47
+ `Broker.fromEnv()` throws `BrokerNotConfigured` when `QONTAIN_BROKER` is unset.
48
+
49
+ The broker token is sent as `X-Qontain-Token`, so `Authorization` stays free for
50
+ the agent's own API keys. `callTool(name)` with no arguments sends JSON `null`.
51
+
52
+ A channel receiver runs only for deliveries the broker signed with this
53
+ agent's `QONTAIN_WIRE_KEY` (set by qontain; `new Agent(name, port, wireKey)`
54
+ overrides it) within the last 300 seconds and not seen before; anything else
55
+ gets 401, so a local process posting to the agent's port cannot pose as
56
+ another agent. Without a key every delivery is refused. Plain routes are not
57
+ signed: anything that can reach the port can call them.
58
+
59
+ `Agent` answers request bodies over 8 MiB with 413. Throw
60
+ `new AgentError(status, message)` from a handler to reply with that status; any
61
+ other error is logged with `console.error` and the caller gets a 500 with a
62
+ generic message.
63
+
64
+ The Python README has a table of how names map across the Python,
65
+ TypeScript and Rust SDKs. Differences: TypeScript `listen()` binds and serves
66
+ in one call (Python's `server()` and Rust's `bind()` return a bound server
67
+ first), and Rust has one `BrokerError::Denied` variant with a `DenialKind`
68
+ instead of a class per status.
69
+
70
+ ```
71
+ npm install
72
+ npm run typecheck
73
+ npm test
74
+ npm run build # emits dist/
75
+ ```
@@ -0,0 +1,51 @@
1
+ import { type IncomingHttpHeaders, type Server } from "node:http";
2
+ export declare const HEALTH_PATH = "/health";
3
+ export declare const SOURCE_HEADER = "x-qontain-source-agent";
4
+ export declare const CHANNEL_HEADER = "x-qontain-channel";
5
+ export declare const TIMESTAMP_HEADER = "x-qontain-timestamp";
6
+ export declare const DELIVERY_HEADER = "x-qontain-delivery";
7
+ export declare const SIGNATURE_HEADER = "x-qontain-signature";
8
+ export declare const WIRE_KEY_ENV = "QONTAIN_WIRE_KEY";
9
+ export declare const MAX_SKEW_SECS = 300;
10
+ export declare const MAX_BODY_BYTES: number;
11
+ export type Handler = (body: unknown) => unknown | Promise<unknown>;
12
+ export type ChannelHandler = (message: unknown, sourceAgent: string | undefined) => unknown | Promise<unknown>;
13
+ /** The signature the broker sends with a wire delivery. */
14
+ export declare function signDelivery(key: string, method: string, path: string, sender: string, channel: string, timestamp: string, delivery: string, body: Uint8Array): string;
15
+ /**
16
+ * Checks that a delivery was signed by the broker with this agent's wire
17
+ * key, recently, and not seen before.
18
+ */
19
+ export declare class WireVerifier {
20
+ #private;
21
+ constructor(key: string | undefined);
22
+ /** undefined if the delivery is authentic, else why it is refused. */
23
+ check(method: string, path: string, headers: IncomingHttpHeaders, body: Uint8Array, nowSecs?: number): string | undefined;
24
+ }
25
+ /** Throw from a handler to reply `status` with `message` to the caller. */
26
+ export declare class AgentError extends Error {
27
+ readonly status: number;
28
+ constructor(status: number, message: string);
29
+ }
30
+ /**
31
+ * HTTP server for an agent's declared ports: request handlers, wire
32
+ * (channel) receivers, and the `/health` endpoint qontain probes.
33
+ *
34
+ * Channel deliveries are verified with `wireKey` (default: the
35
+ * `QONTAIN_WIRE_KEY` qontain sets) before the handler runs; without a key
36
+ * every delivery is refused.
37
+ */
38
+ export declare class Agent {
39
+ #private;
40
+ readonly name: string;
41
+ readonly port: number;
42
+ private readonly routes;
43
+ constructor(name: string, port?: number, wireKey?: string | undefined);
44
+ /** Register `fn(body) -> reply` for POST `path`. */
45
+ route(path: string, fn: Handler): this;
46
+ /** Register `fn(message, sourceAgent) -> reply` for wire channel `name`. */
47
+ channel(name: string, fn: ChannelHandler): this;
48
+ private add;
49
+ /** Start listening; resolves once bound (port 0 picks a free port). */
50
+ listen(port?: number, host?: string): Promise<Server>;
51
+ }
package/dist/agent.js ADDED
@@ -0,0 +1,194 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ export const HEALTH_PATH = "/health";
4
+ export const SOURCE_HEADER = "x-qontain-source-agent";
5
+ export const CHANNEL_HEADER = "x-qontain-channel";
6
+ export const TIMESTAMP_HEADER = "x-qontain-timestamp";
7
+ export const DELIVERY_HEADER = "x-qontain-delivery";
8
+ export const SIGNATURE_HEADER = "x-qontain-signature";
9
+ export const WIRE_KEY_ENV = "QONTAIN_WIRE_KEY";
10
+ export const MAX_SKEW_SECS = 300;
11
+ export const MAX_BODY_BYTES = 8 << 20;
12
+ /** The signature the broker sends with a wire delivery. */
13
+ export function signDelivery(key, method, path, sender, channel, timestamp, delivery, body) {
14
+ const bodyHash = createHash("sha256").update(body).digest("hex");
15
+ const canonical = ["qontain-wire-v1", method, path, sender, channel, timestamp, delivery, bodyHash].join("\n");
16
+ return `v1=${createHmac("sha256", key).update(canonical).digest("hex")}`;
17
+ }
18
+ /**
19
+ * Checks that a delivery was signed by the broker with this agent's wire
20
+ * key, recently, and not seen before.
21
+ */
22
+ export class WireVerifier {
23
+ #key;
24
+ #seen = new Map();
25
+ constructor(key) {
26
+ this.#key = key || undefined;
27
+ }
28
+ /** undefined if the delivery is authentic, else why it is refused. */
29
+ check(method, path, headers, body, nowSecs = Date.now() / 1000) {
30
+ if (this.#key === undefined)
31
+ return `${WIRE_KEY_ENV} is not set: wire deliveries cannot be verified`;
32
+ const [sender, channel, timestamp, delivery, signature] = [
33
+ SOURCE_HEADER,
34
+ CHANNEL_HEADER,
35
+ TIMESTAMP_HEADER,
36
+ DELIVERY_HEADER,
37
+ SIGNATURE_HEADER,
38
+ ].map((h) => single(headers[h]));
39
+ if (!sender || !channel || !timestamp || !delivery || !signature)
40
+ return "unsigned wire delivery";
41
+ if (!/^[0-9]+$/.test(timestamp))
42
+ return "invalid wire delivery timestamp";
43
+ if (Math.abs(nowSecs - Number(timestamp)) > MAX_SKEW_SECS)
44
+ return "stale wire delivery";
45
+ const expected = Buffer.from(signDelivery(this.#key, method, path, sender, channel, timestamp, delivery, body));
46
+ const given = Buffer.from(signature);
47
+ if (expected.length !== given.length || !timingSafeEqual(expected, given)) {
48
+ return "invalid wire delivery signature";
49
+ }
50
+ for (const [id, at] of this.#seen)
51
+ if (nowSecs - at > 2 * MAX_SKEW_SECS)
52
+ this.#seen.delete(id);
53
+ if (this.#seen.has(delivery))
54
+ return "replayed wire delivery";
55
+ this.#seen.set(delivery, nowSecs);
56
+ return undefined;
57
+ }
58
+ }
59
+ function single(value) {
60
+ return Array.isArray(value) ? value[0] : value;
61
+ }
62
+ /** Throw from a handler to reply `status` with `message` to the caller. */
63
+ export class AgentError extends Error {
64
+ status;
65
+ constructor(status, message) {
66
+ super(message);
67
+ this.name = "AgentError";
68
+ this.status = status;
69
+ }
70
+ }
71
+ /**
72
+ * HTTP server for an agent's declared ports: request handlers, wire
73
+ * (channel) receivers, and the `/health` endpoint qontain probes.
74
+ *
75
+ * Channel deliveries are verified with `wireKey` (default: the
76
+ * `QONTAIN_WIRE_KEY` qontain sets) before the handler runs; without a key
77
+ * every delivery is refused.
78
+ */
79
+ export class Agent {
80
+ name;
81
+ port;
82
+ routes = new Map();
83
+ #verifier;
84
+ constructor(name, port = 8080, wireKey = process.env[WIRE_KEY_ENV]) {
85
+ this.name = name;
86
+ this.port = port;
87
+ this.#verifier = new WireVerifier(wireKey);
88
+ }
89
+ /** Register `fn(body) -> reply` for POST `path`. */
90
+ route(path, fn) {
91
+ this.add(path, { signed: false, fn: (body) => fn(body) });
92
+ return this;
93
+ }
94
+ /** Register `fn(message, sourceAgent) -> reply` for wire channel `name`. */
95
+ channel(name, fn) {
96
+ this.add(`/channels/${name}`, { signed: true, fn });
97
+ return this;
98
+ }
99
+ add(path, route) {
100
+ if (!path.startsWith("/"))
101
+ throw new Error(`handler path "${path}" must start with '/'`);
102
+ if (path === HEALTH_PATH)
103
+ throw new Error(`handler path "${HEALTH_PATH}" is reserved for the health check`);
104
+ if (this.routes.has(path))
105
+ throw new Error(`duplicate handler path "${path}"`);
106
+ this.routes.set(path, route);
107
+ }
108
+ /** Start listening; resolves once bound (port 0 picks a free port). */
109
+ listen(port = this.port, host = "0.0.0.0") {
110
+ const routes = new Map(this.routes);
111
+ const verifier = this.#verifier;
112
+ const server = createServer((req, res) => {
113
+ handle(routes, verifier, req, res).catch((e) => {
114
+ if (e instanceof AgentError)
115
+ return replyError(res, e.status, e.message);
116
+ console.error(`qontain agent: handler for ${req.url} failed:`, e);
117
+ replyError(res, 500, "internal error");
118
+ });
119
+ });
120
+ return new Promise((resolve, reject) => {
121
+ server.once("error", reject);
122
+ server.listen(port, host, () => resolve(server));
123
+ });
124
+ }
125
+ }
126
+ async function handle(routes, verifier, req, res) {
127
+ const path = (req.url ?? "/").split("?")[0];
128
+ if (req.method === "GET" && path === HEALTH_PATH)
129
+ return reply(res, 200, "ok", "text/plain");
130
+ const route = req.method === "POST" ? routes.get(path) : undefined;
131
+ if (!route)
132
+ return reply(res, 404, "", "text/plain");
133
+ const raw = await readBody(req);
134
+ if (raw === undefined) {
135
+ res.setHeader("connection", "close");
136
+ res.on("finish", () => req.socket.destroy());
137
+ return replyError(res, 413, `request body over ${MAX_BODY_BYTES} bytes`);
138
+ }
139
+ let source;
140
+ if (route.signed) {
141
+ const refused = verifier.check("POST", path, req.headers, raw);
142
+ if (refused !== undefined) {
143
+ console.warn(`qontain agent: refused a wire delivery to ${path}: ${refused}`);
144
+ return replyError(res, 401, refused);
145
+ }
146
+ source = single(req.headers[SOURCE_HEADER]);
147
+ }
148
+ const result = await route.fn(decode(raw), source);
149
+ if (result === undefined || result === null)
150
+ return reply(res, 204, "", "text/plain");
151
+ if (result instanceof Uint8Array)
152
+ return reply(res, 200, result, "application/octet-stream");
153
+ if (typeof result === "string")
154
+ return reply(res, 200, result, "text/plain; charset=utf-8");
155
+ return reply(res, 200, JSON.stringify(result), "application/json");
156
+ }
157
+ /** The request body, or undefined once it passes MAX_BODY_BYTES. */
158
+ function readBody(req) {
159
+ return new Promise((resolve, reject) => {
160
+ if (Number(req.headers["content-length"]) > MAX_BODY_BYTES)
161
+ return resolve(undefined);
162
+ const chunks = [];
163
+ let size = 0;
164
+ req.on("data", (chunk) => {
165
+ if (size > MAX_BODY_BYTES)
166
+ return;
167
+ size += chunk.length;
168
+ if (size > MAX_BODY_BYTES)
169
+ return resolve(undefined);
170
+ chunks.push(chunk);
171
+ });
172
+ req.on("end", () => resolve(Buffer.concat(chunks)));
173
+ req.on("error", reject);
174
+ });
175
+ }
176
+ function reply(res, status, body, contentType) {
177
+ res.writeHead(status, { "content-type": contentType, "content-length": Buffer.byteLength(body) });
178
+ res.end(body);
179
+ }
180
+ function replyError(res, status, message) {
181
+ if (res.headersSent)
182
+ return void res.destroy();
183
+ reply(res, status, JSON.stringify({ error: { type: "agent_error", message } }), "application/json");
184
+ }
185
+ function decode(raw) {
186
+ if (raw.length === 0)
187
+ return undefined;
188
+ try {
189
+ return JSON.parse(raw.toString("utf8"));
190
+ }
191
+ catch {
192
+ return new Uint8Array(raw);
193
+ }
194
+ }
@@ -0,0 +1,23 @@
1
+ import { BROKER_ENV } from "./errors.ts";
2
+ export { BROKER_ENV };
3
+ export declare const TOKEN_ENV = "QONTAIN_BROKER_TOKEN";
4
+ export declare const TOKEN_HEADER = "x-qontain-token";
5
+ export interface BrokerOptions {
6
+ token?: string;
7
+ timeoutMs?: number;
8
+ }
9
+ /** Client for the qontain egress broker an agent runs behind. */
10
+ export declare class Broker {
11
+ readonly url: string;
12
+ readonly token: string | undefined;
13
+ readonly timeoutMs: number;
14
+ constructor(url: string, options?: BrokerOptions);
15
+ static fromEnv(env?: Record<string, string | undefined>, timeoutMs?: number): Broker;
16
+ /** URL that reaches `https://{host}/{path}` through the broker. */
17
+ egressUrl(host: string, path?: string): string;
18
+ /** Invoke a host-side tool; counts against the agent's max_tool_calls. */
19
+ callTool(name: string, args?: unknown): Promise<unknown>;
20
+ /** Send a message on a declared wire; resolves to the receiving agent's reply. */
21
+ send(channel: string, message: unknown): Promise<unknown>;
22
+ private post;
23
+ }
package/dist/broker.js ADDED
@@ -0,0 +1,80 @@
1
+ import { BROKER_ENV, BrokerError, BrokerNotConfigured, BrokerTransportError, errorFor, isRecord } from "./errors.js";
2
+ export { BROKER_ENV };
3
+ export const TOKEN_ENV = "QONTAIN_BROKER_TOKEN";
4
+ export const TOKEN_HEADER = "x-qontain-token";
5
+ /** Client for the qontain egress broker an agent runs behind. */
6
+ export class Broker {
7
+ url;
8
+ token;
9
+ timeoutMs;
10
+ constructor(url, options = {}) {
11
+ this.url = url.replace(/\/+$/, "");
12
+ this.token = options.token || undefined;
13
+ this.timeoutMs = options.timeoutMs ?? 60_000;
14
+ }
15
+ static fromEnv(env = process.env, timeoutMs) {
16
+ const url = env[BROKER_ENV];
17
+ if (!url)
18
+ throw new BrokerNotConfigured();
19
+ return new Broker(url, { token: env[TOKEN_ENV], timeoutMs });
20
+ }
21
+ /** URL that reaches `https://{host}/{path}` through the broker. */
22
+ egressUrl(host, path = "") {
23
+ return `${this.url}/egress/${host}/${path.replace(/^\/+/, "")}`;
24
+ }
25
+ /** Invoke a host-side tool; counts against the agent's max_tool_calls. */
26
+ callTool(name, args) {
27
+ return this.post(`/tools/${encodeURIComponent(name)}`, args);
28
+ }
29
+ /** Send a message on a declared wire; resolves to the receiving agent's reply. */
30
+ send(channel, message) {
31
+ return this.post(`/channels/${encodeURIComponent(channel)}`, message);
32
+ }
33
+ async post(path, payload) {
34
+ const headers = { "content-type": "application/json" };
35
+ if (this.token)
36
+ headers[TOKEN_HEADER] = this.token;
37
+ let status;
38
+ let text;
39
+ try {
40
+ const response = await fetch(this.url + path, {
41
+ method: "POST",
42
+ headers,
43
+ body: JSON.stringify(payload ?? null),
44
+ signal: AbortSignal.timeout(this.timeoutMs),
45
+ });
46
+ status = response.status;
47
+ text = await response.text();
48
+ }
49
+ catch (e) {
50
+ throw new BrokerTransportError(`broker request failed: ${describe(e)}`, e);
51
+ }
52
+ const body = decode(text);
53
+ if (status < 200 || status >= 300) {
54
+ throw errorFor(status, body) ?? new BrokerError(status, message(body));
55
+ }
56
+ return body;
57
+ }
58
+ }
59
+ function describe(e) {
60
+ if (!(e instanceof Error))
61
+ return String(e);
62
+ if (e.name === "TimeoutError")
63
+ return "timed out";
64
+ return e.cause instanceof Error ? `${e.message} (${e.cause.message})` : e.message;
65
+ }
66
+ function decode(text) {
67
+ if (!text)
68
+ return undefined;
69
+ try {
70
+ return JSON.parse(text);
71
+ }
72
+ catch {
73
+ return text;
74
+ }
75
+ }
76
+ function message(body) {
77
+ if (isRecord(body) && isRecord(body.error))
78
+ return String(body.error.message ?? "");
79
+ return typeof body === "string" ? body : JSON.stringify(body);
80
+ }
@@ -0,0 +1,55 @@
1
+ export declare const BROKER_ENV = "QONTAIN_BROKER";
2
+ /**
3
+ * The qontain broker refused or could not complete a request. `status` is
4
+ * the HTTP status, or undefined when no response arrived.
5
+ */
6
+ export declare class BrokerError extends Error {
7
+ readonly status: number | undefined;
8
+ readonly detail: unknown;
9
+ constructor(status: number | undefined, message: string, detail?: unknown, options?: ErrorOptions);
10
+ /** True when the broker's policy refused the request. */
11
+ get isDenial(): boolean;
12
+ }
13
+ /** The broker's policy refused the request. */
14
+ export declare class BrokerDenied extends BrokerError {
15
+ get isDenial(): boolean;
16
+ }
17
+ /** Missing or wrong QONTAIN_BROKER_TOKEN. */
18
+ export declare class BrokerAuthError extends BrokerDenied {
19
+ }
20
+ /** Destination, tool or channel not allowed for this agent. */
21
+ export declare class PolicyDenied extends BrokerDenied {
22
+ }
23
+ /** Replay mode has no more recorded responses for this agent. */
24
+ export declare class ReplayExhausted extends BrokerDenied {
25
+ }
26
+ /** Strict replay has no recorded response to this request (`detail.differed` says why), or only a truncated one. */
27
+ export declare class ReplayDivergence extends BrokerDenied {
28
+ }
29
+ /** The channel message does not match the wire's JSON schema. */
30
+ export declare class SchemaViolation extends BrokerDenied {
31
+ }
32
+ /** Token, cost or tool-call budget is used up. */
33
+ export declare class BudgetExceeded extends BrokerDenied {
34
+ }
35
+ /** No backend is registered on the host for this tool. */
36
+ export declare class ToolUnavailable extends BrokerDenied {
37
+ }
38
+ /** The upstream API, tool backend or receiving agent failed. */
39
+ export declare class UpstreamError extends BrokerDenied {
40
+ }
41
+ /** The broker's circuit breaker is tripped (fleet spend ceiling or kill switch). */
42
+ export declare class BrokerUnavailable extends BrokerDenied {
43
+ }
44
+ /** The request could not be sent or the reply not read, including timeouts. */
45
+ export declare class BrokerTransportError extends BrokerError {
46
+ constructor(message: string, cause?: unknown);
47
+ }
48
+ /** QONTAIN_BROKER is not set. */
49
+ export declare class BrokerNotConfigured extends BrokerError {
50
+ constructor();
51
+ }
52
+ export declare const DENIAL_TYPE = "qontain_egress_denied";
53
+ /** The BrokerDenied a broker response represents, or undefined if it is not a broker denial. */
54
+ export declare function errorFor(status: number, body: unknown): BrokerError | undefined;
55
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
package/dist/errors.js ADDED
@@ -0,0 +1,87 @@
1
+ export const BROKER_ENV = "QONTAIN_BROKER";
2
+ /**
3
+ * The qontain broker refused or could not complete a request. `status` is
4
+ * the HTTP status, or undefined when no response arrived.
5
+ */
6
+ export class BrokerError extends Error {
7
+ status;
8
+ detail;
9
+ constructor(status, message, detail, options) {
10
+ super(status === undefined ? message : `${message} (HTTP ${status})`, options);
11
+ this.name = new.target.name;
12
+ this.status = status;
13
+ this.detail = detail;
14
+ }
15
+ /** True when the broker's policy refused the request. */
16
+ get isDenial() {
17
+ return false;
18
+ }
19
+ }
20
+ /** The broker's policy refused the request. */
21
+ export class BrokerDenied extends BrokerError {
22
+ get isDenial() {
23
+ return true;
24
+ }
25
+ }
26
+ /** Missing or wrong QONTAIN_BROKER_TOKEN. */
27
+ export class BrokerAuthError extends BrokerDenied {
28
+ }
29
+ /** Destination, tool or channel not allowed for this agent. */
30
+ export class PolicyDenied extends BrokerDenied {
31
+ }
32
+ /** Replay mode has no more recorded responses for this agent. */
33
+ export class ReplayExhausted extends BrokerDenied {
34
+ }
35
+ /** Strict replay has no recorded response to this request (`detail.differed` says why), or only a truncated one. */
36
+ export class ReplayDivergence extends BrokerDenied {
37
+ }
38
+ /** The channel message does not match the wire's JSON schema. */
39
+ export class SchemaViolation extends BrokerDenied {
40
+ }
41
+ /** Token, cost or tool-call budget is used up. */
42
+ export class BudgetExceeded extends BrokerDenied {
43
+ }
44
+ /** No backend is registered on the host for this tool. */
45
+ export class ToolUnavailable extends BrokerDenied {
46
+ }
47
+ /** The upstream API, tool backend or receiving agent failed. */
48
+ export class UpstreamError extends BrokerDenied {
49
+ }
50
+ /** The broker's circuit breaker is tripped (fleet spend ceiling or kill switch). */
51
+ export class BrokerUnavailable extends BrokerDenied {
52
+ }
53
+ /** The request could not be sent or the reply not read, including timeouts. */
54
+ export class BrokerTransportError extends BrokerError {
55
+ constructor(message, cause) {
56
+ super(undefined, message, undefined, { cause });
57
+ }
58
+ }
59
+ /** QONTAIN_BROKER is not set. */
60
+ export class BrokerNotConfigured extends BrokerError {
61
+ constructor() {
62
+ super(undefined, `${BROKER_ENV} is not set; is this agent running under qontain with a broker?`);
63
+ }
64
+ }
65
+ const BY_STATUS = {
66
+ 401: BrokerAuthError,
67
+ 403: PolicyDenied,
68
+ 409: ReplayDivergence,
69
+ 410: ReplayExhausted,
70
+ 422: SchemaViolation,
71
+ 429: BudgetExceeded,
72
+ 501: ToolUnavailable,
73
+ 502: UpstreamError,
74
+ 503: BrokerUnavailable,
75
+ };
76
+ export const DENIAL_TYPE = "qontain_egress_denied";
77
+ /** The BrokerDenied a broker response represents, or undefined if it is not a broker denial. */
78
+ export function errorFor(status, body) {
79
+ const error = isRecord(body) ? body.error : undefined;
80
+ if (!isRecord(error) || error.type !== DENIAL_TYPE)
81
+ return undefined;
82
+ const ErrorType = BY_STATUS[status] ?? BrokerDenied;
83
+ return new ErrorType(status, String(error.message ?? ""), error.detail);
84
+ }
85
+ export function isRecord(value) {
86
+ return typeof value === "object" && value !== null && !Array.isArray(value);
87
+ }
@@ -0,0 +1,3 @@
1
+ export { Agent, AgentError, type ChannelHandler, type Handler, signDelivery, WireVerifier } from "./agent.ts";
2
+ export { Broker, type BrokerOptions } from "./broker.ts";
3
+ export { BrokerAuthError, BrokerDenied, BrokerError, BrokerNotConfigured, BrokerTransportError, BrokerUnavailable, BudgetExceeded, PolicyDenied, ReplayDivergence, ReplayExhausted, SchemaViolation, ToolUnavailable, UpstreamError, } from "./errors.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Agent, AgentError, signDelivery, WireVerifier } from "./agent.js";
2
+ export { Broker } from "./broker.js";
3
+ export { BrokerAuthError, BrokerDenied, BrokerError, BrokerNotConfigured, BrokerTransportError, BrokerUnavailable, BudgetExceeded, PolicyDenied, ReplayDivergence, ReplayExhausted, SchemaViolation, ToolUnavailable, UpstreamError, } from "./errors.js";
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "qontain",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "SDK for agents running under the qontain runtime: broker client and agent server",
5
+ "license": "(MIT OR Apache-2.0)",
6
+ "author": "Albin <albin@albyte.ai>",
7
+ "homepage": "https://github.com/albyte-ai/qontain",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/albyte-ai/qontain.git",
11
+ "directory": "sdk/typescript"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/albyte-ai/qontain/issues"
15
+ },
16
+ "keywords": [
17
+ "ai",
18
+ "agents",
19
+ "sandbox",
20
+ "llm",
21
+ "broker",
22
+ "qontain"
23
+ ],
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "LICENSE-MIT",
34
+ "LICENSE-APACHE",
35
+ "NOTICE"
36
+ ],
37
+ "engines": {
38
+ "node": ">=22.18"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.json",
42
+ "typecheck": "tsc -p tsconfig.test.json",
43
+ "test": "node --test test/*.test.ts"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^26.6.6",
47
+ "typescript": "^7.0.2"
48
+ }
49
+ }