@iicp/client 0.2.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 ADDED
@@ -0,0 +1,180 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and its Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or otherwise designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and incorporated
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or in combination with the Work to which such
78
+ Contribution(s) was submitted. If You institute patent litigation
79
+ against any entity (including a cross-claim or counterclaim in a
80
+ lawsuit) alleging that the Work or a Contribution incorporated within
81
+ the Work constitutes direct or contributory patent infringement, then
82
+ any patent licenses granted to You under this License for that Work
83
+ shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text
106
+ file distributed as part of the Derivative Works; within
107
+ the Source form or documentation, if provided along with the
108
+ Derivative Works; or, within a display generated by the
109
+ Derivative Works, if and wherever such third-party notices
110
+ normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License.
112
+ You may add Your own attribution notices within Derivative
113
+ Works that You distribute, alongside or as an addendum to
114
+ the NOTICE text from the Work, provided that such additional
115
+ attribution notices cannot be construed as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, copy, modify, merge,
119
+ publish, distribute, sublicense, and/or sell copies of the Work,
120
+ and to permit persons to whom the Work is furnished to do so, subject
121
+ to Your separate additional terms and conditions.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any conditions of title,
141
+ non-infringement, merchantability, or fitness for a particular
142
+ purpose. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may offer only
163
+ conditions fully consistent with this License to any recipient of
164
+ the Work.
165
+
166
+ END OF TERMS AND CONDITIONS
167
+
168
+ Copyright 2026 Rob Lemumin
169
+
170
+ Licensed under the Apache License, Version 2.0 (the "License");
171
+ you may not use this file except in compliance with the License.
172
+ You may obtain a copy of the License at
173
+
174
+ http://www.apache.org/licenses/LICENSE-2.0
175
+
176
+ Unless required by applicable law or agreed to in writing, software
177
+ distributed under the License is distributed on an "AS IS" BASIS,
178
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
179
+ See the License for the specific language governing permissions and
180
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # iicp-client · TypeScript / JavaScript SDK
2
+
3
+ [![CI](https://github.com/RobLe3/iicp-client-typescript/actions/workflows/ci.yml/badge.svg)](https://github.com/RobLe3/iicp-client-typescript/actions/workflows/ci.yml)
4
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
5
+ [![Protocol](https://img.shields.io/badge/IICP-v1.5-indigo.svg)](https://iicp.network/spec)
6
+ [![npm](https://img.shields.io/badge/npm-iicp--client-red?logo=npm)](https://www.npmjs.com/package/iicp-client)
7
+
8
+ Official TypeScript client library for the [IICP protocol](https://iicp.network) — route AI agent tasks by intent across a self-organising mesh of provider nodes. No central broker. No hardcoded endpoints.
9
+
10
+ Works in **Node.js ≥ 18**, Deno, Bun, and modern browsers with the native Fetch API.
11
+
12
+ ```
13
+ urn:iicp:intent:llm:chat:v1 → discover → select → submit
14
+ ```
15
+
16
+ ---
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install iicp-client
22
+ # yarn add iicp-client
23
+ # pnpm add iicp-client
24
+ ```
25
+
26
+ ---
27
+
28
+ ## Quickstart
29
+
30
+ ```typescript
31
+ import { IicpClient } from "iicp-client";
32
+
33
+ const client = new IicpClient({ directory_url: "https://iicp.network" });
34
+
35
+ // chat() discovers, selects the best node, and submits in one call
36
+ const response = await client.chat(
37
+ [{ role: "user", content: "Hello from IICP!" }],
38
+ );
39
+ console.log(response.choices[0].message.content);
40
+ ```
41
+
42
+ For more control over node selection:
43
+
44
+ ```typescript
45
+ const nodes = await client.discover("urn:iicp:intent:llm:chat:v1");
46
+ if (!nodes.length) throw new Error("No nodes available");
47
+
48
+ const result = await client.submit({
49
+ intent: "urn:iicp:intent:llm:chat:v1",
50
+ payload: { messages: [{ role: "user", content: "Hello!" }] },
51
+ });
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Configuration
57
+
58
+ ```typescript
59
+ import { IicpClient } from "iicp-client";
60
+
61
+ const client = new IicpClient({
62
+ directory_url : "https://iicp.network", // IICP directory
63
+ timeout_ms : 30_000, // max 120 000 (SDK-04)
64
+ region : "eu-central", // prefer nodes in region
65
+ api_token : "your-token", // optional auth token
66
+ });
67
+ ```
68
+
69
+ | Option | Default | Description |
70
+ |--------|---------|-------------|
71
+ | `directory_url` | `"https://iicp.network"` | IICP directory endpoint |
72
+ | `timeout_ms` | `30000` | Request timeout — max 120 000 ms |
73
+ | `region` | `undefined` | Preferred node region |
74
+ | `api_token` | `undefined` | Bearer token for authenticated nodes |
75
+
76
+ ---
77
+
78
+ ## Discover options
79
+
80
+ ```typescript
81
+ const nodes = await client.discover("urn:iicp:intent:llm:chat:v1", {
82
+ region : "eu-central",
83
+ model : "phi3:mini",
84
+ min_reputation: 0.7,
85
+ limit : 5,
86
+ });
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Error handling
92
+
93
+ ```typescript
94
+ import { IicpClient, IicpError } from "iicp-client";
95
+
96
+ const client = new IicpClient();
97
+ try {
98
+ const response = await client.chat([{ role: "user", content: "hi" }]);
99
+ } catch (e) {
100
+ if (e instanceof IicpError) {
101
+ console.error(`[${e.code}] ${e.message} (HTTP ${e.status_code})`);
102
+ }
103
+ }
104
+ ```
105
+
106
+ Error codes match the [IICP error reference](https://iicp.network/docs/error-reference) — e.g. `task_timeout`, `capacity_exceeded`, `no_nodes_available`.
107
+
108
+ ---
109
+
110
+ ## SDK conformance
111
+
112
+ | Rule | Description | Status |
113
+ |------|-------------|--------|
114
+ | SDK-01 | discover → select → submit pipeline with node retry | ✓ |
115
+ | SDK-02 | `task_id` auto-generated (UUID v4) | ✓ |
116
+ | SDK-03 | Intent URN pattern validation | ✓ |
117
+ | SDK-04 | `timeout_ms` capped at 120 000 ms | ✓ |
118
+ | SDK-05 | Retry on 429 / 503 with exponential back-off | ✓ |
119
+ | SDK-06 | W3C `traceparent` propagation | ✓ |
120
+
121
+ Conformance tier: `iicp:sdk:v1` (spec S.14) · [Request a badge](https://iicp.network/conformance)
122
+
123
+ ---
124
+
125
+ ## Development
126
+
127
+ ```bash
128
+ npm install # install deps
129
+ npm run typecheck # tsc strict
130
+ npm test # 25 unit tests
131
+ npm run build # emit to dist/
132
+ ```
133
+
134
+ ---
135
+
136
+ ## Links
137
+
138
+ - [Protocol spec](https://iicp.network/spec) — full IICP specification
139
+ - [Node setup guide](https://iicp.network/docs/node-setup) — run your own node
140
+ - [Error reference](https://iicp.network/docs/error-reference) — all error codes
141
+ - [iicp-client-python](https://github.com/RobLe3/iicp-client-python) — Python SDK
142
+ - [iicp-client-rust](https://github.com/RobLe3/iicp-client-rust) — Rust SDK
143
+
144
+ ---
145
+
146
+ Apache 2.0 · [iicp.network](https://iicp.network)
@@ -0,0 +1,25 @@
1
+ /**
2
+ * IicpClient — primary entrypoint for the IICP TypeScript SDK (ADR-016 §1).
3
+ * Implements SDK-01..SDK-06 conformance rules.
4
+ */
5
+ import type { ChatMessage, ChatOptions, ChatResponse, ClientConfig, DiscoverOptions, Node, TaskRequest, TaskResponse } from "./types.js";
6
+ export declare class IicpClient {
7
+ private readonly cfg;
8
+ constructor(config?: Partial<ClientConfig>);
9
+ /** Discover nodes capable of handling the given intent. */
10
+ discover(intent: string, opts?: DiscoverOptions, traceparent?: string): Promise<Node[]>;
11
+ /**
12
+ * Discover → select best node → submit task.
13
+ * Retries up to MAX_RETRIES on transient errors (SDK-01).
14
+ */
15
+ submit(req: TaskRequest): Promise<TaskResponse>;
16
+ /**
17
+ * Discover → select best LLM node → submit chat task via /v1/task (SDK-01/02).
18
+ * Uses submit() internally so the full discover→select→retry pipeline applies.
19
+ */
20
+ chat(messages: ChatMessage[], opts?: ChatOptions): Promise<ChatResponse>;
21
+ private _validateIntent;
22
+ private _get;
23
+ private _post;
24
+ }
25
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,IAAI,EACJ,WAAW,EACX,YAAY,EACb,MAAM,YAAY,CAAC;AAcpB,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;gBAEvB,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC;IAgB1C,2DAA2D;IACrD,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,eAAe,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IA+B7F;;;OAGG;IACG,MAAM,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;IAsErD;;;OAGG;IACG,IAAI,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;IAsD9E,OAAO,CAAC,eAAe;YAST,IAAI;YAoCJ,KAAK;CAqDpB"}
package/dist/client.js ADDED
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ /**
3
+ * IicpClient — primary entrypoint for the IICP TypeScript SDK (ADR-016 §1).
4
+ * Implements SDK-01..SDK-06 conformance rules.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.IicpClient = void 0;
8
+ const node_crypto_1 = require("node:crypto");
9
+ const errors_js_1 = require("./errors.js");
10
+ const INTENT_RE = /^urn:iicp:intent:[a-z0-9_:/-]+$/;
11
+ const MAX_TIMEOUT_MS = 120_000;
12
+ const DEFAULT_TIMEOUT_MS = 30_000;
13
+ const MAX_RETRIES = 3;
14
+ const TRANSIENT_STATUSES = new Set([429, 502, 503, 504]);
15
+ const DEFAULT_CONFIG = {
16
+ directory_url: "https://iicp.network",
17
+ timeout_ms: DEFAULT_TIMEOUT_MS,
18
+ tls_verify: true,
19
+ };
20
+ class IicpClient {
21
+ cfg;
22
+ constructor(config) {
23
+ const merged = { ...DEFAULT_CONFIG, ...config };
24
+ // SDK-04: reject oversized timeouts at construction time
25
+ if (merged.timeout_ms > MAX_TIMEOUT_MS) {
26
+ throw new errors_js_1.IicpError(`timeout_ms must be ≤ ${MAX_TIMEOUT_MS}; got ${merged.timeout_ms}`, "SDK-04");
27
+ }
28
+ this.cfg = merged;
29
+ }
30
+ // ------------------------------------------------------------------
31
+ // Public async API
32
+ // ------------------------------------------------------------------
33
+ /** Discover nodes capable of handling the given intent. */
34
+ async discover(intent, opts, traceparent) {
35
+ const o = opts ?? {};
36
+ const params = new URLSearchParams();
37
+ params.set("intent", intent);
38
+ params.set("limit", String(Math.min(o.limit ?? 10, 50)));
39
+ const region = o.region ?? this.cfg.region;
40
+ if (region)
41
+ params.set("region", region);
42
+ if (o.qos)
43
+ params.set("qos", o.qos);
44
+ if (o.min_reputation !== undefined)
45
+ params.set("min_reputation", String(o.min_reputation));
46
+ const data = await this._get(`${this.cfg.directory_url}/api/v1/discover?${params}`, 5_000, traceparent);
47
+ const raw = data.nodes ?? [];
48
+ return raw.map((n) => {
49
+ const node = n;
50
+ return {
51
+ node_id: String(node.node_id),
52
+ endpoint: String(node.endpoint ?? ""),
53
+ score: Number(node.score ?? 0),
54
+ available: Boolean(node.available ?? true),
55
+ region: String(node.region ?? ""),
56
+ latency_estimate_ms: node.latency_estimate_ms,
57
+ reputation_score: node.reputation_score,
58
+ };
59
+ });
60
+ }
61
+ /**
62
+ * Discover → select best node → submit task.
63
+ * Retries up to MAX_RETRIES on transient errors (SDK-01).
64
+ */
65
+ async submit(req) {
66
+ this._validateIntent(req.intent);
67
+ const tp = _traceparent(); // SDK-06: shared trace across discover + submit
68
+ const nodes = await this.discover(req.intent, {
69
+ region: req.constraints?.region ?? this.cfg.region,
70
+ qos: req.constraints?.qos,
71
+ min_reputation: req.constraints?.min_reputation,
72
+ }, tp);
73
+ if (nodes.length === 0) {
74
+ throw new errors_js_1.IicpError(`No nodes available for intent: ${req.intent}`, "SDK-03", { component: "directory" });
75
+ }
76
+ const node = nodes[0];
77
+ const taskId = req.task_id ?? (0, node_crypto_1.randomUUID)();
78
+ const body = {
79
+ task_id: taskId,
80
+ intent: req.intent,
81
+ payload: req.payload,
82
+ constraints: req.constraints ?? {},
83
+ };
84
+ const headers = {
85
+ "Content-Type": "application/json",
86
+ };
87
+ if (req.auth?.token) {
88
+ headers["Authorization"] = `Bearer ${req.auth.token}`;
89
+ }
90
+ else if (this.cfg.api_token) {
91
+ headers["Authorization"] = `Bearer ${this.cfg.api_token}`;
92
+ }
93
+ let lastErr;
94
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
95
+ try {
96
+ const data = await this._post(`${node.endpoint}/v1/task`, body, req.constraints?.timeout_ms ?? this.cfg.timeout_ms, headers, tp);
97
+ return {
98
+ task_id: taskId,
99
+ result: data.result,
100
+ status: String(data.status ?? "ok"),
101
+ metrics: data.metrics,
102
+ };
103
+ }
104
+ catch (err) {
105
+ if (err instanceof errors_js_1.IicpError &&
106
+ err.status_code !== undefined &&
107
+ TRANSIENT_STATUSES.has(err.status_code)) {
108
+ lastErr = err;
109
+ // SDK-01: exponential back-off on transient errors
110
+ await _sleep(200 * 2 ** attempt);
111
+ continue;
112
+ }
113
+ throw err;
114
+ }
115
+ }
116
+ throw lastErr;
117
+ }
118
+ /**
119
+ * Discover → select best LLM node → submit chat task via /v1/task (SDK-01/02).
120
+ * Uses submit() internally so the full discover→select→retry pipeline applies.
121
+ */
122
+ async chat(messages, opts) {
123
+ const o = opts ?? {};
124
+ const intent = o.intent ?? "urn:iicp:intent:llm:chat:v1";
125
+ const resp = await this.submit({
126
+ intent,
127
+ payload: {
128
+ messages,
129
+ ...(o.model ? { model: o.model } : {}),
130
+ ...(o.max_tokens !== undefined ? { max_tokens: o.max_tokens } : {}),
131
+ ...(o.temperature !== undefined ? { temperature: o.temperature } : {}),
132
+ },
133
+ constraints: {
134
+ timeout_ms: o.timeout_ms ?? this.cfg.timeout_ms,
135
+ ...(o.region ? { region: o.region } : {}),
136
+ ...(o.min_reputation !== undefined ? { min_reputation: o.min_reputation } : {}),
137
+ },
138
+ });
139
+ const result = (resp.result ?? {});
140
+ const rawChoices = result.choices ?? [];
141
+ const choices = rawChoices.map((c, i) => {
142
+ const ch = c;
143
+ const msg = ch.message;
144
+ return {
145
+ index: i,
146
+ message: {
147
+ role: msg?.role ?? "assistant",
148
+ content: msg?.content ?? "",
149
+ },
150
+ finish_reason: String(ch.finish_reason ?? "stop"),
151
+ };
152
+ });
153
+ const rawUsage = result.usage;
154
+ const usage = rawUsage
155
+ ? {
156
+ prompt_tokens: rawUsage.prompt_tokens ?? 0,
157
+ completion_tokens: rawUsage.completion_tokens ?? 0,
158
+ total_tokens: rawUsage.total_tokens ?? 0,
159
+ }
160
+ : undefined;
161
+ return {
162
+ id: resp.task_id,
163
+ choices,
164
+ usage,
165
+ node_id: String(result.node_id ?? ""),
166
+ };
167
+ }
168
+ // ------------------------------------------------------------------
169
+ // Private helpers
170
+ // ------------------------------------------------------------------
171
+ _validateIntent(intent) {
172
+ if (!INTENT_RE.test(intent)) {
173
+ throw new errors_js_1.IicpError(`Invalid intent URN: "${intent}" — must match urn:iicp:intent:*`, "SDK-02");
174
+ }
175
+ }
176
+ async _get(url, timeoutMs, traceparent) {
177
+ const controller = new AbortController();
178
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
179
+ try {
180
+ const res = await fetch(url, {
181
+ headers: { Accept: "application/json", traceparent: traceparent ?? _traceparent() },
182
+ signal: controller.signal,
183
+ });
184
+ if (!res.ok) {
185
+ const body = await res.text().catch(() => "");
186
+ throw new errors_js_1.IicpError(`GET ${url} returned ${res.status}: ${body.slice(0, 200)}`, "SDK-05", { status_code: res.status, component: "directory" });
187
+ }
188
+ return (await res.json());
189
+ }
190
+ catch (err) {
191
+ if (err instanceof errors_js_1.IicpError)
192
+ throw err;
193
+ if (err.name === "AbortError") {
194
+ throw new errors_js_1.IicpError(`Request timed out after ${timeoutMs}ms`, "SDK-01", { component: "directory" });
195
+ }
196
+ throw new errors_js_1.IicpError(`Network error: ${err.message}`, "SDK-05", { cause: err, component: "directory" });
197
+ }
198
+ finally {
199
+ clearTimeout(timer);
200
+ }
201
+ }
202
+ async _post(url, body, timeoutMs, extraHeaders, traceparent) {
203
+ const controller = new AbortController();
204
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
205
+ try {
206
+ const res = await fetch(url, {
207
+ method: "POST",
208
+ headers: {
209
+ "Content-Type": "application/json",
210
+ Accept: "application/json",
211
+ traceparent: traceparent ?? _traceparent(),
212
+ ...extraHeaders,
213
+ },
214
+ body: JSON.stringify(body),
215
+ signal: controller.signal,
216
+ });
217
+ if (!res.ok) {
218
+ const text = await res.text().catch(() => "");
219
+ let code = "SDK-05";
220
+ try {
221
+ const j = JSON.parse(text);
222
+ if (j.error)
223
+ code = j.error;
224
+ }
225
+ catch { /* ignore */ }
226
+ throw new errors_js_1.IicpError(`POST ${url} returned ${res.status}: ${text.slice(0, 200)}`, code, { status_code: res.status, component: "adapter" });
227
+ }
228
+ return (await res.json());
229
+ }
230
+ catch (err) {
231
+ if (err instanceof errors_js_1.IicpError)
232
+ throw err;
233
+ if (err.name === "AbortError") {
234
+ throw new errors_js_1.IicpError(`Request timed out after ${timeoutMs}ms`, "SDK-01", { component: "adapter" });
235
+ }
236
+ throw new errors_js_1.IicpError(`Network error: ${err.message}`, "SDK-05", { cause: err, component: "adapter" });
237
+ }
238
+ finally {
239
+ clearTimeout(timer);
240
+ }
241
+ }
242
+ }
243
+ exports.IicpClient = IicpClient;
244
+ function _sleep(ms) {
245
+ return new Promise((resolve) => setTimeout(resolve, ms));
246
+ }
247
+ /** Generate a W3C traceparent header value (SDK-06). */
248
+ function _traceparent() {
249
+ const traceId = (0, node_crypto_1.randomUUID)().replace(/-/g, "");
250
+ const parentId = (0, node_crypto_1.randomUUID)().replace(/-/g, "").slice(0, 16);
251
+ return `00-${traceId}-${parentId}-01`;
252
+ }
253
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,6CAAyC;AAEzC,2CAAwC;AAYxC,MAAM,SAAS,GAAG,iCAAiC,CAAC;AACpD,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;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;QACtB,CAAC;IACH,CAAC;CACF;AAzRD,gCAyRC;AAED,SAAS,MAAM,CAAC,EAAU;IACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED,wDAAwD;AACxD,SAAS,YAAY;IACnB,MAAM,OAAO,GAAG,IAAA,wBAAU,GAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAC/C,MAAM,QAAQ,GAAG,IAAA,wBAAU,GAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC7D,OAAO,MAAM,OAAO,IAAI,QAAQ,KAAK,CAAC;AACxC,CAAC"}
@@ -0,0 +1,15 @@
1
+ /** IICP error class — SDK-05 / SDK-06 compliant (ADR-016 §3) */
2
+ export declare class IicpError extends Error {
3
+ /** IICP error code (e.g. SDK-01, IICP-E010). Always set (SDK-06). */
4
+ readonly code: string;
5
+ /** HTTP status code when the error came from a network response. */
6
+ readonly status_code?: number;
7
+ /** Component that raised the error (directory | adapter | proxy | sdk). */
8
+ readonly component?: string;
9
+ constructor(message: string, code: string, opts?: {
10
+ status_code?: number;
11
+ component?: string;
12
+ cause?: unknown;
13
+ });
14
+ }
15
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAEhE,qBAAa,SAAU,SAAQ,KAAK;IAClC,qEAAqE;IACrE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,2EAA2E;IAC3E,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;gBAEhB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAChD,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB;CAOF"}
package/dist/errors.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /** IICP error class — SDK-05 / SDK-06 compliant (ADR-016 §3) */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.IicpError = void 0;
5
+ class IicpError extends Error {
6
+ /** IICP error code (e.g. SDK-01, IICP-E010). Always set (SDK-06). */
7
+ code;
8
+ /** HTTP status code when the error came from a network response. */
9
+ status_code;
10
+ /** Component that raised the error (directory | adapter | proxy | sdk). */
11
+ component;
12
+ constructor(message, code, opts) {
13
+ super(message, opts?.cause ? { cause: opts.cause } : undefined);
14
+ this.name = "IicpError";
15
+ this.code = code;
16
+ this.status_code = opts?.status_code;
17
+ this.component = opts?.component ?? "sdk";
18
+ }
19
+ }
20
+ exports.IicpError = IicpError;
21
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";AAAA,gEAAgE;;;AAEhE,MAAa,SAAU,SAAQ,KAAK;IAClC,qEAAqE;IAC5D,IAAI,CAAS;IACtB,oEAAoE;IAC3D,WAAW,CAAU;IAC9B,2EAA2E;IAClE,SAAS,CAAU;IAE5B,YAAY,OAAe,EAAE,IAAY,EAAE,IAI1C;QACC,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAChE,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,WAAW,GAAG,IAAI,EAAE,WAAW,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,IAAI,EAAE,SAAS,IAAI,KAAK,CAAC;IAC5C,CAAC;CACF;AAnBD,8BAmBC"}
@@ -0,0 +1,6 @@
1
+ export { IicpClient } from "./client.js";
2
+ export { IicpError } from "./errors.js";
3
+ export { IicpNode } from "./node.js";
4
+ export type { NodeConfig, ServeOptions, TaskHandler } from "./node.js";
5
+ export type { ChatMessage, ChatOptions, ChatResponse, ChatChoice, ChatUsage, ClientConfig, DiscoverOptions, Node, TaskAuth, TaskConstraints, TaskMetrics, TaskRequest, TaskResponse, } from "./types.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACvE,YAAY,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,UAAU,EACV,SAAS,EACT,YAAY,EACZ,eAAe,EACf,IAAI,EACJ,QAAQ,EACR,eAAe,EACf,WAAW,EACX,WAAW,EACX,YAAY,GACb,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IicpNode = exports.IicpError = exports.IicpClient = void 0;
4
+ var client_js_1 = require("./client.js");
5
+ Object.defineProperty(exports, "IicpClient", { enumerable: true, get: function () { return client_js_1.IicpClient; } });
6
+ var errors_js_1 = require("./errors.js");
7
+ Object.defineProperty(exports, "IicpError", { enumerable: true, get: function () { return errors_js_1.IicpError; } });
8
+ var node_js_1 = require("./node.js");
9
+ Object.defineProperty(exports, "IicpNode", { enumerable: true, get: function () { return node_js_1.IicpNode; } });
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AAAhC,uGAAA,UAAU,OAAA;AACnB,yCAAwC;AAA/B,sGAAA,SAAS,OAAA;AAClB,qCAAqC;AAA5B,mGAAA,QAAQ,OAAA"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * IICP provider node — registration, heartbeats, and task serving.
3
+ *
4
+ * Endpoints served by `IicpNode.serve()`:
5
+ * POST /v1/task — task handler (IICP-E021 concurrency gate,
6
+ * IICP-E011 nonce replay, W3C traceparent)
7
+ * GET /iicp/health — liveness / capacity (always 200)
8
+ * GET /metrics — Prometheus text (503 if prom-client absent)
9
+ */
10
+ export interface NodeConfig {
11
+ nodeId: string;
12
+ endpoint: string;
13
+ intent: string;
14
+ model?: string;
15
+ region?: string;
16
+ capabilities?: string[];
17
+ directoryUrl?: string;
18
+ timeoutMs?: number;
19
+ /** Maximum concurrent tasks; excess → 429 IICP-E021. Default: 4. */
20
+ maxConcurrent?: number;
21
+ }
22
+ export interface ServeOptions {
23
+ host?: string;
24
+ port?: number;
25
+ nodeToken?: string;
26
+ }
27
+ export type TaskHandler = (task: Record<string, unknown>) => Promise<Record<string, unknown>>;
28
+ export declare class IicpNode {
29
+ private readonly _cfg;
30
+ private _activeTasks;
31
+ private _nonces;
32
+ private _prom;
33
+ private _tasksCounter;
34
+ private _latencyHistogram;
35
+ private _tokensCounter;
36
+ private _promLoaded;
37
+ constructor(config: NodeConfig);
38
+ register(): Promise<string>;
39
+ heartbeat(nodeToken: string): Promise<void>;
40
+ private _checkNonce;
41
+ private _ensureProm;
42
+ serve(handler: TaskHandler, options?: ServeOptions): () => void;
43
+ private _handleHealth;
44
+ private _handleMetrics;
45
+ private _handleTask;
46
+ }
47
+ //# sourceMappingURL=node.d.ts.map
@@ -0,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WAAW,EAAE,OAAO,GAAE,YAAiB,GAAG,MAAM,IAAI;IAuCnE,OAAO,CAAC,aAAa;IAoBrB,OAAO,CAAC,cAAc;IAmBtB,OAAO,CAAC,WAAW;CAqFpB"}
package/dist/node.js ADDED
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * IICP provider node — registration, heartbeats, and task serving.
5
+ *
6
+ * Endpoints served by `IicpNode.serve()`:
7
+ * POST /v1/task — task handler (IICP-E021 concurrency gate,
8
+ * IICP-E011 nonce replay, W3C traceparent)
9
+ * GET /iicp/health — liveness / capacity (always 200)
10
+ * GET /metrics — Prometheus text (503 if prom-client absent)
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.IicpNode = void 0;
14
+ const http = require("node:http");
15
+ const DEFAULT_DIRECTORY = "https://iicp.network/api";
16
+ const HEARTBEAT_INTERVAL_MS = 30_000;
17
+ const NONCE_TTL_MS = 300_000;
18
+ // ── IicpNode ──────────────────────────────────────────────────────────────────
19
+ class IicpNode {
20
+ _cfg;
21
+ _activeTasks = 0;
22
+ _nonces = new Map(); // nonce → expiry timestamp (ms)
23
+ _prom = null;
24
+ _tasksCounter = null;
25
+ _latencyHistogram = null;
26
+ _tokensCounter = null;
27
+ _promLoaded = false;
28
+ constructor(config) {
29
+ this._cfg = {
30
+ nodeId: config.nodeId,
31
+ endpoint: config.endpoint,
32
+ intent: config.intent,
33
+ model: config.model,
34
+ region: config.region,
35
+ capabilities: config.capabilities ?? [],
36
+ directoryUrl: config.directoryUrl ?? DEFAULT_DIRECTORY,
37
+ timeoutMs: config.timeoutMs ?? 5_000,
38
+ maxConcurrent: config.maxConcurrent ?? 4,
39
+ };
40
+ }
41
+ // ── Directory operations ───────────────────────────────────────────────────
42
+ async register() {
43
+ const body = {
44
+ node_id: this._cfg.nodeId,
45
+ endpoint: this._cfg.endpoint,
46
+ intent: this._cfg.intent,
47
+ };
48
+ if (this._cfg.model)
49
+ body.model = this._cfg.model;
50
+ if (this._cfg.region)
51
+ body.region = this._cfg.region;
52
+ if (this._cfg.capabilities.length)
53
+ body.capabilities = this._cfg.capabilities;
54
+ const resp = await fetch(`${this._cfg.directoryUrl.replace(/\/$/, "")}/v1/register`, {
55
+ method: "POST",
56
+ headers: { "Content-Type": "application/json" },
57
+ body: JSON.stringify(body),
58
+ signal: AbortSignal.timeout(this._cfg.timeoutMs),
59
+ });
60
+ if (!resp.ok)
61
+ throw new Error(`Registration failed: ${resp.status}`);
62
+ const data = (await resp.json());
63
+ const token = (data.node_token ?? data.token);
64
+ if (!token)
65
+ throw new Error(`Directory did not return node_token: ${JSON.stringify(data)}`);
66
+ return token;
67
+ }
68
+ async heartbeat(nodeToken) {
69
+ const resp = await fetch(`${this._cfg.directoryUrl.replace(/\/$/, "")}/api/v1/heartbeat`, {
70
+ method: "POST",
71
+ headers: { "Content-Type": "application/json" },
72
+ body: JSON.stringify({
73
+ node_id: this._cfg.nodeId,
74
+ node_token: nodeToken,
75
+ status: "available",
76
+ }),
77
+ signal: AbortSignal.timeout(this._cfg.timeoutMs),
78
+ });
79
+ if (!resp.ok)
80
+ throw new Error(`Heartbeat failed: ${resp.status}`);
81
+ }
82
+ // ── Nonce replay protection ────────────────────────────────────────────────
83
+ _checkNonce(nonce) {
84
+ if (!nonce)
85
+ return true;
86
+ const now = Date.now();
87
+ // Evict expired nonces
88
+ for (const [k, exp] of this._nonces) {
89
+ if (exp < now)
90
+ this._nonces.delete(k);
91
+ }
92
+ if (this._nonces.has(nonce))
93
+ return false;
94
+ this._nonces.set(nonce, now + NONCE_TTL_MS);
95
+ return true;
96
+ }
97
+ // ── Prometheus (lazy, optional) ────────────────────────────────────────────
98
+ async _ensureProm() {
99
+ if (this._promLoaded)
100
+ return;
101
+ this._promLoaded = true;
102
+ try {
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
+ this._prom = await eval('import("prom-client")');
105
+ this._tasksCounter = new this._prom.Counter({
106
+ name: "iicp_tasks_total",
107
+ help: "Total IICP tasks handled",
108
+ labelNames: ["status", "intent", "qos"],
109
+ });
110
+ this._latencyHistogram = new this._prom.Histogram({
111
+ name: "iicp_task_latency_ms",
112
+ help: "IICP task processing latency (ms)",
113
+ labelNames: ["intent", "qos"],
114
+ buckets: [50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000, 30_000],
115
+ });
116
+ this._tokensCounter = new this._prom.Counter({
117
+ name: "iicp_tokens_used_total",
118
+ help: "Total tokens consumed",
119
+ labelNames: ["intent"],
120
+ });
121
+ }
122
+ catch {
123
+ this._prom = null;
124
+ }
125
+ }
126
+ // ── serve() ────────────────────────────────────────────────────────────────
127
+ serve(handler, options = {}) {
128
+ const host = options.host ?? "0.0.0.0";
129
+ const port = options.port ?? 8020;
130
+ const nodeToken = options.nodeToken;
131
+ // Load Prometheus in background (non-blocking)
132
+ this._ensureProm().catch(() => undefined);
133
+ const server = http.createServer((req, res) => {
134
+ if (req.method === "GET" && req.url === "/iicp/health") {
135
+ this._handleHealth(res);
136
+ }
137
+ else if (req.method === "GET" && req.url === "/metrics") {
138
+ this._handleMetrics(res);
139
+ }
140
+ else if (req.method === "POST" && req.url === "/v1/task") {
141
+ this._handleTask(req, res, handler);
142
+ }
143
+ else {
144
+ res.writeHead(404, { "Content-Type": "application/json" });
145
+ res.end(JSON.stringify({ error: "not_found" }));
146
+ }
147
+ });
148
+ server.listen(port, host);
149
+ let hbTimer;
150
+ if (nodeToken) {
151
+ hbTimer = setInterval(() => {
152
+ this.heartbeat(nodeToken).catch(() => undefined);
153
+ }, HEARTBEAT_INTERVAL_MS);
154
+ }
155
+ return () => {
156
+ if (hbTimer)
157
+ clearInterval(hbTimer);
158
+ server.closeAllConnections?.();
159
+ server.close();
160
+ };
161
+ }
162
+ // ── GET /iicp/health ───────────────────────────────────────────────────────
163
+ _handleHealth(res) {
164
+ const active = this._activeTasks;
165
+ const max = this._cfg.maxConcurrent;
166
+ const body = JSON.stringify({
167
+ status: "ok",
168
+ node_id: this._cfg.nodeId,
169
+ region: this._cfg.region ?? "unknown",
170
+ load: max > 0 ? active / max : 0,
171
+ active_jobs: active,
172
+ max_concurrent: max,
173
+ available: active < max,
174
+ model: this._cfg.model ?? "",
175
+ intent: this._cfg.intent,
176
+ });
177
+ res.writeHead(200, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
178
+ res.end(body);
179
+ }
180
+ // ── GET /metrics ───────────────────────────────────────────────────────────
181
+ _handleMetrics(res) {
182
+ if (!this._prom) {
183
+ const body = "prom-client not installed";
184
+ res.writeHead(503, { "Content-Type": "text/plain" });
185
+ res.end(body);
186
+ return;
187
+ }
188
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
189
+ this._prom.register.metrics().then((metrics) => {
190
+ res.writeHead(200, { "Content-Type": this._prom.register.contentType });
191
+ res.end(metrics);
192
+ }).catch(() => {
193
+ res.writeHead(503, { "Content-Type": "text/plain" });
194
+ res.end("metrics unavailable");
195
+ });
196
+ }
197
+ // ── POST /v1/task ──────────────────────────────────────────────────────────
198
+ _handleTask(req, res, handler) {
199
+ // Concurrency gate — IICP-E021
200
+ if (this._activeTasks >= this._cfg.maxConcurrent) {
201
+ const body = JSON.stringify({
202
+ error: { code: "IICP-E021", message: "capacity_exceeded", retry_after_ms: 2000 },
203
+ });
204
+ res.writeHead(429, {
205
+ "Content-Type": "application/json",
206
+ "Retry-After": "2",
207
+ "Content-Length": Buffer.byteLength(body),
208
+ });
209
+ res.end(body);
210
+ return;
211
+ }
212
+ this._activeTasks++;
213
+ const t0 = Date.now();
214
+ const chunks = [];
215
+ req.on("data", (chunk) => chunks.push(chunk));
216
+ req.on("end", () => {
217
+ let task = {};
218
+ try {
219
+ task = JSON.parse(Buffer.concat(chunks).toString() || "{}");
220
+ }
221
+ catch {
222
+ this._activeTasks--;
223
+ res.writeHead(400, { "Content-Type": "application/json" });
224
+ res.end(JSON.stringify({ error: { code: "IICP-E000", message: "invalid JSON" } }));
225
+ return;
226
+ }
227
+ // Nonce replay — IICP-E011
228
+ if (!this._checkNonce(task.nonce)) {
229
+ this._activeTasks--;
230
+ const body = JSON.stringify({ error: { code: "IICP-E011", message: "replay_detected" } });
231
+ res.writeHead(409, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
232
+ res.end(body);
233
+ return;
234
+ }
235
+ // W3C traceparent propagation
236
+ const tp = req.headers["traceparent"];
237
+ if (tp)
238
+ task._trace = { traceparent: tp };
239
+ const intent = task.intent ?? this._cfg.intent;
240
+ const constraints = task.constraints;
241
+ const qos = constraints?.qos_class ?? "best_effort";
242
+ const taskId = task.task_id ?? "";
243
+ handler(task)
244
+ .then((result) => {
245
+ this._activeTasks--;
246
+ const latencyMs = Date.now() - t0;
247
+ if (this._tasksCounter) {
248
+ this._tasksCounter
249
+ .labels("completed", intent, qos).inc();
250
+ }
251
+ if (this._latencyHistogram) {
252
+ this._latencyHistogram.labels(intent, qos).observe(latencyMs);
253
+ }
254
+ const tokens = result.usage?.total_tokens ?? 0;
255
+ if (tokens && this._tokensCounter) {
256
+ this._tokensCounter
257
+ .labels(intent).inc(tokens);
258
+ }
259
+ const body = JSON.stringify({ task_id: taskId, status: "completed", ...result });
260
+ res.writeHead(200, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
261
+ res.end(body);
262
+ })
263
+ .catch((err) => {
264
+ this._activeTasks--;
265
+ if (this._tasksCounter) {
266
+ this._tasksCounter
267
+ .labels("error", intent, qos).inc();
268
+ }
269
+ const body = JSON.stringify({ task_id: taskId, status: "error", error: { message: err.message } });
270
+ res.writeHead(500, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
271
+ res.end(body);
272
+ });
273
+ });
274
+ }
275
+ }
276
+ exports.IicpNode = IicpNode;
277
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";AAAA,sCAAsC;AACtC;;;;;;;;GAQG;;;A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AC;iBACD,KAAK,CAAC,CAAC,GAAU,EAAE,EAAE;gBACpB,IAAI,CAAC,YAAY,EAAE,CAAC;gBACpB,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;oBACtB,IAAI,CAAC,aAAoF;yBACvF,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;gBACxC,CAAC;gBACD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;gBACnG,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACtG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA1RD,4BA0RC"}
@@ -0,0 +1,87 @@
1
+ /** IICP TypeScript SDK — type definitions (ADR-016 §1) */
2
+ export interface ClientConfig {
3
+ /** Directory URL. Default: https://iicp.network */
4
+ directory_url: string;
5
+ /** Request timeout in ms. Max 120 000 (SDK-04). Default: 30 000 */
6
+ timeout_ms: number;
7
+ /** Preferred region for node selection. */
8
+ region?: string;
9
+ /** Bearer token for authenticated routes. */
10
+ api_token?: string;
11
+ /** Verify TLS certificates. Default: true */
12
+ tls_verify: boolean;
13
+ }
14
+ export interface TaskConstraints {
15
+ region?: string;
16
+ qos?: string;
17
+ timeout_ms?: number;
18
+ min_reputation?: number;
19
+ }
20
+ export interface TaskAuth {
21
+ token: string;
22
+ mode?: "bearer" | "node";
23
+ }
24
+ export interface TaskMetrics {
25
+ latency_ms?: number;
26
+ tokens_used?: number;
27
+ node_id?: string;
28
+ }
29
+ export interface TaskRequest {
30
+ /** Intent URN — must match urn:iicp:intent:* (SDK-02) */
31
+ intent: string;
32
+ payload: Record<string, unknown>;
33
+ constraints?: TaskConstraints;
34
+ auth?: TaskAuth;
35
+ task_id?: string;
36
+ }
37
+ export interface TaskResponse {
38
+ task_id: string;
39
+ result: unknown;
40
+ status: string;
41
+ metrics?: TaskMetrics;
42
+ }
43
+ export interface DiscoverOptions {
44
+ limit?: number;
45
+ region?: string;
46
+ qos?: string;
47
+ min_reputation?: number;
48
+ }
49
+ export interface Node {
50
+ node_id: string;
51
+ endpoint: string;
52
+ score: number;
53
+ available: boolean;
54
+ region: string;
55
+ latency_estimate_ms?: number;
56
+ reputation_score?: number;
57
+ }
58
+ export interface ChatMessage {
59
+ role: "user" | "assistant" | "system";
60
+ content: string;
61
+ }
62
+ export interface ChatUsage {
63
+ prompt_tokens: number;
64
+ completion_tokens: number;
65
+ total_tokens: number;
66
+ }
67
+ export interface ChatChoice {
68
+ index: number;
69
+ message: ChatMessage;
70
+ finish_reason: string;
71
+ }
72
+ export interface ChatResponse {
73
+ id: string;
74
+ choices: ChatChoice[];
75
+ usage?: ChatUsage;
76
+ node_id?: string;
77
+ }
78
+ export interface ChatOptions {
79
+ intent?: string;
80
+ region?: string;
81
+ timeout_ms?: number;
82
+ min_reputation?: number;
83
+ model?: string;
84
+ max_tokens?: number;
85
+ temperature?: number;
86
+ }
87
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAE1D,MAAM,WAAW,YAAY;IAC3B,mDAAmD;IACnD,aAAa,EAAE,MAAM,CAAC;IACtB,mEAAmE;IACnE,UAAU,EAAE,MAAM,CAAC;IACnB,2CAA2C;IAC3C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6CAA6C;IAC7C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6CAA6C;IAC7C,UAAU,EA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gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,QAAQ,CAAC;IACtC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,SAAS;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,WAAW,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ /** IICP TypeScript SDK — type definitions (ADR-016 §1) */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA,0DAA0D"}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@iicp/client",
3
+ "version": "0.2.0",
4
+ "description": "Official TypeScript/JavaScript SDK for the IICP protocol (ADR-016)",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "tsc --project tsconfig.json",
15
+ "test": "tsx --test tests/*.test.ts",
16
+ "typecheck": "tsc --noEmit"
17
+ },
18
+ "keywords": ["iicp", "ai-agents", "protocol", "sdk"],
19
+ "license": "Apache-2.0",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/RobLe3/iicp-client-typescript.git"
23
+ },
24
+ "homepage": "https://iicp.network",
25
+ "bugs": {
26
+ "url": "https://github.com/RobLe3/iicp-client-typescript/issues"
27
+ },
28
+ "engines": {
29
+ "node": ">=18.0.0"
30
+ },
31
+ "peerDependencies": {
32
+ "prom-client": ">=14"
33
+ },
34
+ "peerDependenciesMeta": {
35
+ "prom-client": { "optional": true }
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "^5.4.0",
39
+ "@types/node": "^20.0.0",
40
+ "tsx": "^4.0.0",
41
+ "prom-client": "^15"
42
+ },
43
+ "files": ["dist", "README.md"],
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "registry": "https://registry.npmjs.org/"
47
+ }
48
+ }