@iicp/web-node 0.2.3 → 0.2.5
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 +83 -61
- package/README.md +19 -0
- package/dist/browserNodeProvider.d.ts +8 -0
- package/dist/browserNodeProvider.js +14 -8
- package/dist/build-manifest.json +4 -4
- package/dist/dispatchTicket.d.ts +12 -0
- package/dist/dispatchTicket.js +14 -0
- package/dist/effectiveCapability.d.ts +76 -0
- package/dist/effectiveCapability.js +200 -0
- package/dist/iicpConsumer.d.ts +15 -20
- package/dist/iicpConsumer.js +65 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/runtimeIdentity.d.ts +25 -0
- package/dist/runtimeIdentity.js +105 -0
- package/dist/version.d.ts +3 -3
- package/dist/version.js +2 -2
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
|
|
1
2
|
Apache License
|
|
2
3
|
Version 2.0, January 2004
|
|
3
4
|
http://www.apache.org/licenses/
|
|
@@ -32,33 +33,36 @@
|
|
|
32
33
|
not limited to compiled object code, generated documentation,
|
|
33
34
|
and conversions to other media types.
|
|
34
35
|
|
|
35
|
-
"Work" shall mean the work of authorship
|
|
36
|
-
the License, as indicated by a
|
|
37
|
-
|
|
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).
|
|
38
40
|
|
|
39
41
|
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
42
|
form, that is based on (or derived from) the Work and for which the
|
|
41
|
-
editorial revisions, annotations, elaborations, or other
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
44
|
represent, as a whole, an original work of authorship. For the purposes
|
|
43
45
|
of this License, Derivative Works shall not include works that remain
|
|
44
46
|
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
-
the Work and
|
|
46
|
-
|
|
47
|
-
"Contribution" shall mean
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
or
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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.
|
|
62
66
|
|
|
63
67
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
68
|
this License, each Contributor hereby grants to You a perpetual,
|
|
@@ -74,21 +78,22 @@
|
|
|
74
78
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
79
|
where such license applies only to those patent claims licensable
|
|
76
80
|
by such Contributor that are necessarily infringed by their
|
|
77
|
-
Contribution(s) alone or
|
|
78
|
-
Contribution(s) was submitted. If You
|
|
79
|
-
against any entity (including a
|
|
80
|
-
lawsuit) alleging that the Work
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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.
|
|
84
89
|
|
|
85
90
|
4. Redistribution. You may reproduce and distribute copies of the
|
|
86
91
|
Work or Derivative Works thereof in any medium, with or without
|
|
87
92
|
modifications, and in Source or Object form, provided that You
|
|
88
93
|
meet the following conditions:
|
|
89
94
|
|
|
90
|
-
(a) You must give any other recipients of the Work or
|
|
91
|
-
Works a copy of this License; and
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
92
97
|
|
|
93
98
|
(b) You must cause any modified files to carry prominent notices
|
|
94
99
|
stating that You changed the files; and
|
|
@@ -100,25 +105,28 @@
|
|
|
100
105
|
the Derivative Works; and
|
|
101
106
|
|
|
102
107
|
(d) If the Work includes a "NOTICE" text file as part of its
|
|
103
|
-
distribution,
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
the
|
|
108
|
-
Derivative Works;
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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.
|
|
122
130
|
|
|
123
131
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
124
132
|
any Contribution intentionally submitted for inclusion in the Work
|
|
@@ -137,10 +145,10 @@
|
|
|
137
145
|
agreed to in writing, Licensor provides the Work (and each
|
|
138
146
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
139
147
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
140
|
-
implied, including, without limitation, any
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
appropriateness of using 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
|
|
144
152
|
risks associated with Your exercise of permissions under this License.
|
|
145
153
|
|
|
146
154
|
8. Limitation of Liability. In no event and under no legal theory,
|
|
@@ -148,24 +156,38 @@
|
|
|
148
156
|
unless required by applicable law (such as deliberate and grossly
|
|
149
157
|
negligent acts) or agreed to in writing, shall any Contributor be
|
|
150
158
|
liable to You for damages, including any direct, indirect, special,
|
|
151
|
-
incidental, or
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
152
160
|
result of this License or out of the use or inability to use the
|
|
153
161
|
Work (including but not limited to damages for loss of goodwill,
|
|
154
|
-
work stoppage, computer failure or malfunction, or all
|
|
155
|
-
commercial damages or losses), even if such Contributor
|
|
156
|
-
advised of the possibility of such damages.
|
|
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.
|
|
157
165
|
|
|
158
166
|
9. Accepting Warranty or Additional Liability. While redistributing
|
|
159
167
|
the Work or Derivative Works thereof, You may choose to offer,
|
|
160
168
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
161
169
|
or other liability obligations and/or rights consistent with this
|
|
162
|
-
License. However, in accepting such obligations, You may
|
|
163
|
-
|
|
164
|
-
|
|
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.
|
|
165
176
|
|
|
166
177
|
END OF TERMS AND CONDITIONS
|
|
167
178
|
|
|
168
|
-
|
|
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]
|
|
169
191
|
|
|
170
192
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
171
193
|
you may not use this file except in compliance with the License.
|
package/README.md
CHANGED
|
@@ -5,6 +5,11 @@ from the network *and* **serve** a model from a browser tab. ESM, built on the p
|
|
|
5
5
|
native `fetch` / `SubtleCrypto` / WebGPU (and runs in Node ≥18). The browser
|
|
6
6
|
client refuses keyless providers rather than silently sending plaintext.
|
|
7
7
|
|
|
8
|
+
IICP supplies intent resolution and provider eligibility/selection. MCP, A2A,
|
|
9
|
+
HTTP or another negotiated binding may then execute the selected task. See the
|
|
10
|
+
public [protocol positioning](https://github.com/RobLe3/IICP/blob/main/standards/IICP_PROTOCOL_POSITIONING.md)
|
|
11
|
+
and [adjacent-protocol comparison](https://github.com/RobLe3/IICP/blob/main/standards/PROTOCOL_COMPARISON_2026-08-15.md).
|
|
12
|
+
|
|
8
13
|
```
|
|
9
14
|
npm install @iicp/web-node
|
|
10
15
|
```
|
|
@@ -36,6 +41,20 @@ When the chosen node advertises an encryption key (`nodeCxKey(node)`), the paylo
|
|
|
36
41
|
no opt-out. A node that does not advertise `cx_public_key`/`public_key` is refused before
|
|
37
42
|
any network send so browser use cannot silently fall back to plaintext.
|
|
38
43
|
|
|
44
|
+
## Runtime self-description
|
|
45
|
+
|
|
46
|
+
Browser `chat()` calls add a small IICP runtime identity context by default. It
|
|
47
|
+
tells the selected model that it is being accessed through IICP, identifies the
|
|
48
|
+
active intent and browser package version, and includes a model or capability
|
|
49
|
+
fact only when it comes from the selected node's advertisement. It does not
|
|
50
|
+
expose endpoints, full node identities, candidate sets, scores or credentials,
|
|
51
|
+
and it is not a prompt-injection security boundary.
|
|
52
|
+
|
|
53
|
+
Set `runtime_identity: { mode: "disabled" }` to preserve the application
|
|
54
|
+
messages without the capsule, or use `mode: "required"` to refuse when a
|
|
55
|
+
supported instruction channel is unavailable. Non-chat operations and the
|
|
56
|
+
plaintext envelope helper remain unchanged.
|
|
57
|
+
|
|
39
58
|
## Serve — be a node from the browser
|
|
40
59
|
|
|
41
60
|
```ts
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ChatMessage } from "./iicpConsumer.js";
|
|
2
|
+
import type { EffectiveCapability } from "./effectiveCapability.js";
|
|
2
3
|
export interface BrowserProviderRuntime {
|
|
3
4
|
chat(messages: ChatMessage[], opts?: {
|
|
4
5
|
temperature?: number;
|
|
@@ -14,6 +15,9 @@ export interface BrowserProviderConfig {
|
|
|
14
15
|
directoryUrl?: string;
|
|
15
16
|
/** Model name advertised to the directory (the loaded WebLLM model id). */
|
|
16
17
|
model: string;
|
|
18
|
+
/** Complete service-path variants. When present, these replace the legacy
|
|
19
|
+
* text-only browser advertisement without merging fields across variants. */
|
|
20
|
+
effectiveCapabilities?: EffectiveCapability[];
|
|
17
21
|
region?: string;
|
|
18
22
|
onLog?: (line: string) => void;
|
|
19
23
|
/** Called after each served task with the running total. */
|
|
@@ -32,6 +36,10 @@ export interface BrowserProviderDiagnostic {
|
|
|
32
36
|
tasks_served: number;
|
|
33
37
|
}
|
|
34
38
|
export { BROWSER_NODE_SDK_VERSION } from "./version.js";
|
|
39
|
+
/** Resolve the exact variants sent to the directory. Explicit effective
|
|
40
|
+
* capabilities take precedence; the historical browser default is preserved
|
|
41
|
+
* for callers that do not opt in. */
|
|
42
|
+
export declare function advertisedBrowserCapabilities(explicit: readonly EffectiveCapability[], model: string): EffectiveCapability[];
|
|
35
43
|
/**
|
|
36
44
|
* Coarse region autodetect from the browser's timezone (no network, no
|
|
37
45
|
* geolocation permission). Matches the mesh's region convention
|
|
@@ -21,6 +21,19 @@ import { createCxKeyPair, decryptPayload } from "./cxConfidentiality.js";
|
|
|
21
21
|
import { BROWSER_NODE_SDK_COMPATIBILITY_VERSION, BROWSER_NODE_SDK_VERSION, BROWSER_NODE_VERSION, } from "./version.js";
|
|
22
22
|
const CHAT_INTENT = "urn:iicp:intent:llm:chat:v1";
|
|
23
23
|
export { BROWSER_NODE_SDK_VERSION } from "./version.js";
|
|
24
|
+
/** Resolve the exact variants sent to the directory. Explicit effective
|
|
25
|
+
* capabilities take precedence; the historical browser default is preserved
|
|
26
|
+
* for callers that do not opt in. */
|
|
27
|
+
export function advertisedBrowserCapabilities(explicit, model) {
|
|
28
|
+
return explicit.length > 0
|
|
29
|
+
? explicit.map((capability) => ({ ...capability }))
|
|
30
|
+
: [{
|
|
31
|
+
intent: CHAT_INTENT,
|
|
32
|
+
models: [model],
|
|
33
|
+
max_tokens: 1024,
|
|
34
|
+
input_modalities: ["text"],
|
|
35
|
+
}];
|
|
36
|
+
}
|
|
24
37
|
/**
|
|
25
38
|
* Coarse region autodetect from the browser's timezone (no network, no
|
|
26
39
|
* geolocation permission). Matches the mesh's region convention
|
|
@@ -261,14 +274,7 @@ export class BrowserNodeProvider {
|
|
|
261
274
|
node_id: this.nodeId,
|
|
262
275
|
endpoint,
|
|
263
276
|
region: this.cfg.region ?? detectRegion(),
|
|
264
|
-
capabilities: [
|
|
265
|
-
{
|
|
266
|
-
intent: CHAT_INTENT,
|
|
267
|
-
models: [this.cfg.model],
|
|
268
|
-
max_tokens: 1024,
|
|
269
|
-
input_modalities: ["text"],
|
|
270
|
-
},
|
|
271
|
-
],
|
|
277
|
+
capabilities: advertisedBrowserCapabilities(this.cfg.effectiveCapabilities ?? [], this.cfg.model),
|
|
272
278
|
limits: { max_concurrent: 1, tokens_per_min: 6000 },
|
|
273
279
|
transport_method: "turn_relay",
|
|
274
280
|
exposure_mode: "relay_required",
|
package/dist/build-manifest.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": "iicp.browser_build_provenance.v1",
|
|
3
3
|
"package": "@iicp/web-node",
|
|
4
|
-
"implementation_version": "0.2.
|
|
5
|
-
"sdk_compatibility_version": "0.7.
|
|
6
|
-
"source_commit": "
|
|
7
|
-
"lockfile_sha256": "
|
|
4
|
+
"implementation_version": "0.2.5",
|
|
5
|
+
"sdk_compatibility_version": "0.7.102",
|
|
6
|
+
"source_commit": "6f28256d0d67cf08beddadbc762dbd339786fcd8",
|
|
7
|
+
"lockfile_sha256": "1a398bdcc85e5a650a394aac26851a04c44bd3e6ec9c8c1c359d4d3015338a7e"
|
|
8
8
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface DispatchTicketClaims {
|
|
2
|
+
v: number;
|
|
3
|
+
typ: string;
|
|
4
|
+
iss: string;
|
|
5
|
+
aud: string;
|
|
6
|
+
jti: string;
|
|
7
|
+
node_id: string;
|
|
8
|
+
intent: string;
|
|
9
|
+
iat: number;
|
|
10
|
+
exp: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function verifyDispatchTicket(token: string, keyHex: string, issuer: string, nodeId: string, intent: string, nowSec?: number): DispatchTicketClaims | null;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
2
|
+
import { hexToBytes } from "@noble/hashes/utils.js";
|
|
3
|
+
const DOMAIN = "iicp:dispatch-route-ticket:v1\n";
|
|
4
|
+
function b64(value) { const text = value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4); const raw = atob(text); return Uint8Array.from(raw, c => c.charCodeAt(0)); }
|
|
5
|
+
export function verifyDispatchTicket(token, keyHex, issuer, nodeId, intent, nowSec = Math.floor(Date.now() / 1000)) { const [payload, sig, ...extra] = token.split("."); if (!payload || !sig || extra.length || sig.length !== 128)
|
|
6
|
+
return null; try {
|
|
7
|
+
if (!ed25519.verify(hexToBytes(sig), new TextEncoder().encode(DOMAIN + payload), hexToBytes(keyHex)))
|
|
8
|
+
return null;
|
|
9
|
+
const c = JSON.parse(new TextDecoder().decode(b64(payload)));
|
|
10
|
+
return c.v === 1 && c.typ === "dispatch-route-ticket" && c.iss === issuer && c.aud === "iicp.directory.dispatch" && c.node_id === nodeId && c.intent === intent && c.exp > nowSec && /^[0-9a-f]{24}$/.test(c.jti) ? c : null;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return null;
|
|
14
|
+
} }
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Binding-neutral effective-capability profile primitives.
|
|
2
|
+
*
|
|
3
|
+
* These helpers classify complete service-path variants. They do not perform
|
|
4
|
+
* discovery, policy authorization, final route validation, or dispatch.
|
|
5
|
+
*/
|
|
6
|
+
export declare const EFFECTIVE_CAPABILITY_PROFILE_ID = "urn:iicp:profile:effective-capability:v1";
|
|
7
|
+
export declare const EFFECTIVE_CAPABILITY_SCHEMA_VERSION = "1.0.0";
|
|
8
|
+
export declare const EFFECTIVE_CAPABILITY_REFUSAL: {
|
|
9
|
+
readonly requiredUnknown: "required_capability_unknown";
|
|
10
|
+
readonly requiredUnsupported: "required_capability_unsupported";
|
|
11
|
+
readonly requiredStale: "required_capability_stale";
|
|
12
|
+
readonly limitUnsatisfied: "capability_limit_unsatisfied";
|
|
13
|
+
readonly policyDenied: "capability_policy_denied";
|
|
14
|
+
};
|
|
15
|
+
export interface CapabilityLimit {
|
|
16
|
+
value: number;
|
|
17
|
+
unit: "tokens" | "items" | "bytes" | "milliseconds" | "dimensions";
|
|
18
|
+
}
|
|
19
|
+
export interface CapabilityClaimProvenance {
|
|
20
|
+
source: "heuristic_fallback" | "operator_assertion" | "provider_metadata" | "runtime_introspection" | "conformance_probe";
|
|
21
|
+
observed_at?: string;
|
|
22
|
+
valid_until?: string;
|
|
23
|
+
evidence_ref?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface CapabilityExtension {
|
|
26
|
+
required: boolean;
|
|
27
|
+
value: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** One complete variant; fields from different variants must never be unioned. */
|
|
30
|
+
export interface EffectiveCapability {
|
|
31
|
+
intent: string;
|
|
32
|
+
version?: string;
|
|
33
|
+
phase?: number;
|
|
34
|
+
variant_id?: string;
|
|
35
|
+
models?: string[];
|
|
36
|
+
max_tokens?: number;
|
|
37
|
+
input_modalities?: string[];
|
|
38
|
+
output_modalities?: string[];
|
|
39
|
+
features?: string[];
|
|
40
|
+
execution_capabilities?: string[];
|
|
41
|
+
limits?: Record<string, CapabilityLimit>;
|
|
42
|
+
supported_profiles?: string[];
|
|
43
|
+
claim_provenance?: CapabilityClaimProvenance;
|
|
44
|
+
extensions?: Record<string, CapabilityExtension>;
|
|
45
|
+
}
|
|
46
|
+
export interface CapabilityRequirement {
|
|
47
|
+
class: string;
|
|
48
|
+
id: string;
|
|
49
|
+
}
|
|
50
|
+
export interface CapabilityLimitRequirement {
|
|
51
|
+
id: string;
|
|
52
|
+
operator: "gte" | "lte" | "eq" | string;
|
|
53
|
+
value: number;
|
|
54
|
+
unit: string;
|
|
55
|
+
}
|
|
56
|
+
export interface CapabilityRequirements {
|
|
57
|
+
intent: string;
|
|
58
|
+
requires?: CapabilityRequirement[];
|
|
59
|
+
prefers?: CapabilityRequirement[];
|
|
60
|
+
limits?: CapabilityLimitRequirement[];
|
|
61
|
+
}
|
|
62
|
+
export interface EffectiveCapabilityMatch {
|
|
63
|
+
eligible: boolean;
|
|
64
|
+
variant_ids: Array<string | undefined>;
|
|
65
|
+
preference_unavailable: boolean;
|
|
66
|
+
refusal?: string;
|
|
67
|
+
preserved_extensions: string[];
|
|
68
|
+
}
|
|
69
|
+
export declare function parseEffectiveCapability(raw: unknown): EffectiveCapability;
|
|
70
|
+
export declare function parseEffectiveCapabilityAdvertisement(raw: unknown): EffectiveCapability[];
|
|
71
|
+
export declare function resolveEffectiveCapabilities(options: {
|
|
72
|
+
explicit?: readonly EffectiveCapability[];
|
|
73
|
+
introspected?: readonly EffectiveCapability[];
|
|
74
|
+
heuristic?: readonly EffectiveCapability[];
|
|
75
|
+
}): EffectiveCapability[];
|
|
76
|
+
export declare function matchEffectiveCapabilities(capabilities: readonly EffectiveCapability[], request: CapabilityRequirements, vocabulary: Readonly<Record<string, readonly string[]>>, evaluatedAt: Date, policyDenials?: readonly CapabilityRequirement[]): EffectiveCapabilityMatch;
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/** Binding-neutral effective-capability profile primitives.
|
|
2
|
+
*
|
|
3
|
+
* These helpers classify complete service-path variants. They do not perform
|
|
4
|
+
* discovery, policy authorization, final route validation, or dispatch.
|
|
5
|
+
*/
|
|
6
|
+
export const EFFECTIVE_CAPABILITY_PROFILE_ID = "urn:iicp:profile:effective-capability:v1";
|
|
7
|
+
export const EFFECTIVE_CAPABILITY_SCHEMA_VERSION = "1.0.0";
|
|
8
|
+
export const EFFECTIVE_CAPABILITY_REFUSAL = {
|
|
9
|
+
requiredUnknown: "required_capability_unknown",
|
|
10
|
+
requiredUnsupported: "required_capability_unsupported",
|
|
11
|
+
requiredStale: "required_capability_stale",
|
|
12
|
+
limitUnsatisfied: "capability_limit_unsatisfied",
|
|
13
|
+
policyDenied: "capability_policy_denied",
|
|
14
|
+
};
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
function assertExactKeys(value, allowed, label) {
|
|
19
|
+
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
|
|
20
|
+
if (unknown.length > 0)
|
|
21
|
+
throw new Error(`${label} has unknown field(s): ${unknown.sort().join(", ")}`);
|
|
22
|
+
}
|
|
23
|
+
function stringSet(value, label) {
|
|
24
|
+
if (value === undefined)
|
|
25
|
+
return undefined;
|
|
26
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item.length === 0)) {
|
|
27
|
+
throw new Error(`${label} must be an array of non-empty strings`);
|
|
28
|
+
}
|
|
29
|
+
const result = value;
|
|
30
|
+
if (new Set(result).size !== result.length)
|
|
31
|
+
throw new Error(`${label} must not contain duplicates`);
|
|
32
|
+
return [...result];
|
|
33
|
+
}
|
|
34
|
+
function parseTimestamp(value) {
|
|
35
|
+
const parsed = Date.parse(value);
|
|
36
|
+
if (!Number.isFinite(parsed))
|
|
37
|
+
throw new Error("capability timestamp must be RFC 3339");
|
|
38
|
+
return parsed;
|
|
39
|
+
}
|
|
40
|
+
export function parseEffectiveCapability(raw) {
|
|
41
|
+
if (!isRecord(raw))
|
|
42
|
+
throw new Error("effective capability must be an object");
|
|
43
|
+
assertExactKeys(raw, new Set([
|
|
44
|
+
"intent", "version", "phase", "variant_id", "models", "max_tokens",
|
|
45
|
+
"input_modalities", "output_modalities", "features", "execution_capabilities",
|
|
46
|
+
"limits", "supported_profiles", "claim_provenance", "extensions",
|
|
47
|
+
]), "effective capability");
|
|
48
|
+
if (typeof raw.intent !== "string" || raw.intent.length === 0)
|
|
49
|
+
throw new Error("intent is required");
|
|
50
|
+
if (raw.phase !== undefined && (!Number.isInteger(raw.phase) || raw.phase < 1)) {
|
|
51
|
+
throw new Error("phase must be a positive integer");
|
|
52
|
+
}
|
|
53
|
+
if (raw.max_tokens !== undefined && (!Number.isInteger(raw.max_tokens) || raw.max_tokens < 1)) {
|
|
54
|
+
throw new Error("max_tokens must be a positive integer");
|
|
55
|
+
}
|
|
56
|
+
let limits;
|
|
57
|
+
if (raw.limits !== undefined) {
|
|
58
|
+
if (!isRecord(raw.limits))
|
|
59
|
+
throw new Error("limits must be an object");
|
|
60
|
+
limits = {};
|
|
61
|
+
for (const [id, rawLimit] of Object.entries(raw.limits)) {
|
|
62
|
+
if (!isRecord(rawLimit) || Object.keys(rawLimit).sort().join(",") !== "unit,value") {
|
|
63
|
+
throw new Error("each limit requires only value and unit");
|
|
64
|
+
}
|
|
65
|
+
if (typeof rawLimit.value !== "number" || !Number.isFinite(rawLimit.value) || rawLimit.value < 0) {
|
|
66
|
+
throw new Error("limit value must be a non-negative number");
|
|
67
|
+
}
|
|
68
|
+
if (!["tokens", "items", "bytes", "milliseconds", "dimensions"].includes(String(rawLimit.unit))) {
|
|
69
|
+
throw new Error("limit unit is unsupported");
|
|
70
|
+
}
|
|
71
|
+
limits[id] = { value: rawLimit.value, unit: rawLimit.unit };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
let claim_provenance;
|
|
75
|
+
if (raw.claim_provenance !== undefined) {
|
|
76
|
+
if (!isRecord(raw.claim_provenance))
|
|
77
|
+
throw new Error("claim_provenance must be an object");
|
|
78
|
+
const source = raw.claim_provenance.source;
|
|
79
|
+
const sources = ["heuristic_fallback", "operator_assertion", "provider_metadata", "runtime_introspection", "conformance_probe"];
|
|
80
|
+
if (typeof source !== "string" || !sources.includes(source))
|
|
81
|
+
throw new Error("claim_provenance source is unsupported");
|
|
82
|
+
for (const key of ["observed_at", "valid_until"]) {
|
|
83
|
+
const value = raw.claim_provenance[key];
|
|
84
|
+
if (value !== undefined) {
|
|
85
|
+
if (typeof value !== "string")
|
|
86
|
+
throw new Error(`${key} must be a string`);
|
|
87
|
+
parseTimestamp(value);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
claim_provenance = {
|
|
91
|
+
source: source,
|
|
92
|
+
...(typeof raw.claim_provenance.observed_at === "string" ? { observed_at: raw.claim_provenance.observed_at } : {}),
|
|
93
|
+
...(typeof raw.claim_provenance.valid_until === "string" ? { valid_until: raw.claim_provenance.valid_until } : {}),
|
|
94
|
+
...(typeof raw.claim_provenance.evidence_ref === "string" ? { evidence_ref: raw.claim_provenance.evidence_ref } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
let extensions;
|
|
98
|
+
if (raw.extensions !== undefined) {
|
|
99
|
+
if (!isRecord(raw.extensions))
|
|
100
|
+
throw new Error("extensions must be an object");
|
|
101
|
+
extensions = {};
|
|
102
|
+
for (const [id, rawExtension] of Object.entries(raw.extensions)) {
|
|
103
|
+
if (!isRecord(rawExtension) || Object.keys(rawExtension).sort().join(",") !== "required,value" || typeof rawExtension.required !== "boolean") {
|
|
104
|
+
throw new Error("each extension requires boolean required and value");
|
|
105
|
+
}
|
|
106
|
+
extensions[id] = { required: rawExtension.required, value: rawExtension.value };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
intent: raw.intent,
|
|
111
|
+
...(typeof raw.version === "string" ? { version: raw.version } : {}),
|
|
112
|
+
...(typeof raw.phase === "number" ? { phase: raw.phase } : {}),
|
|
113
|
+
...(typeof raw.variant_id === "string" ? { variant_id: raw.variant_id } : {}),
|
|
114
|
+
...(stringSet(raw.models, "models") ? { models: stringSet(raw.models, "models") } : {}),
|
|
115
|
+
...(typeof raw.max_tokens === "number" ? { max_tokens: raw.max_tokens } : {}),
|
|
116
|
+
...(stringSet(raw.input_modalities, "input_modalities") ? { input_modalities: stringSet(raw.input_modalities, "input_modalities") } : {}),
|
|
117
|
+
...(stringSet(raw.output_modalities, "output_modalities") ? { output_modalities: stringSet(raw.output_modalities, "output_modalities") } : {}),
|
|
118
|
+
...(stringSet(raw.features, "features") ? { features: stringSet(raw.features, "features") } : {}),
|
|
119
|
+
...(stringSet(raw.execution_capabilities, "execution_capabilities") ? { execution_capabilities: stringSet(raw.execution_capabilities, "execution_capabilities") } : {}),
|
|
120
|
+
...(limits ? { limits } : {}),
|
|
121
|
+
...(stringSet(raw.supported_profiles, "supported_profiles") ? { supported_profiles: stringSet(raw.supported_profiles, "supported_profiles") } : {}),
|
|
122
|
+
...(claim_provenance ? { claim_provenance } : {}),
|
|
123
|
+
...(extensions ? { extensions } : {}),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
export function parseEffectiveCapabilityAdvertisement(raw) {
|
|
127
|
+
if (!isRecord(raw))
|
|
128
|
+
throw new Error("advertisement must be an object");
|
|
129
|
+
if (Object.keys(raw).sort().join(",") !== "capabilities,schema_version") {
|
|
130
|
+
throw new Error("advertisement requires only schema_version and capabilities");
|
|
131
|
+
}
|
|
132
|
+
if (raw.schema_version !== EFFECTIVE_CAPABILITY_SCHEMA_VERSION)
|
|
133
|
+
throw new Error("unsupported schema_version");
|
|
134
|
+
if (!Array.isArray(raw.capabilities) || raw.capabilities.length === 0)
|
|
135
|
+
throw new Error("capabilities must be a non-empty array");
|
|
136
|
+
const parsed = raw.capabilities.map(parseEffectiveCapability);
|
|
137
|
+
const identities = parsed.map((item) => `${item.intent}\u0000${item.variant_id ?? ""}`);
|
|
138
|
+
if (new Set(identities).size !== identities.length)
|
|
139
|
+
throw new Error("effective capability variants must be unique");
|
|
140
|
+
return parsed;
|
|
141
|
+
}
|
|
142
|
+
export function resolveEffectiveCapabilities(options) {
|
|
143
|
+
if (options.explicit?.length)
|
|
144
|
+
return [...options.explicit];
|
|
145
|
+
if (options.introspected?.length)
|
|
146
|
+
return [...options.introspected];
|
|
147
|
+
const heuristic = options.heuristic ?? [];
|
|
148
|
+
if (heuristic.some((item) => item.claim_provenance?.source !== "heuristic_fallback")) {
|
|
149
|
+
throw new Error("heuristic capability evidence must be labelled heuristic_fallback");
|
|
150
|
+
}
|
|
151
|
+
return [...heuristic];
|
|
152
|
+
}
|
|
153
|
+
function values(candidate, capabilityClass) {
|
|
154
|
+
switch (capabilityClass) {
|
|
155
|
+
case "input_modality": return candidate.input_modalities;
|
|
156
|
+
case "output_modality": return candidate.output_modalities;
|
|
157
|
+
case "feature": return candidate.features;
|
|
158
|
+
case "execution_capability": return candidate.execution_capabilities;
|
|
159
|
+
case "profile": return candidate.supported_profiles;
|
|
160
|
+
default: return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function refusal(code) {
|
|
164
|
+
return { eligible: false, variant_ids: [], preference_unavailable: false, refusal: code, preserved_extensions: [] };
|
|
165
|
+
}
|
|
166
|
+
export function matchEffectiveCapabilities(capabilities, request, vocabulary, evaluatedAt, policyDenials = []) {
|
|
167
|
+
for (const requirement of request.requires ?? []) {
|
|
168
|
+
if (!vocabulary[requirement.class]?.includes(requirement.id))
|
|
169
|
+
return refusal(EFFECTIVE_CAPABILITY_REFUSAL.requiredUnknown);
|
|
170
|
+
if (policyDenials.some((denial) => denial.class === requirement.class && denial.id === requirement.id)) {
|
|
171
|
+
return refusal(EFFECTIVE_CAPABILITY_REFUSAL.policyDenied);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
let candidates = capabilities.filter((candidate) => candidate.intent === request.intent && (request.requires ?? []).every((required) => values(candidate, required.class)?.includes(required.id)));
|
|
175
|
+
if (candidates.length === 0)
|
|
176
|
+
return refusal(EFFECTIVE_CAPABILITY_REFUSAL.requiredUnsupported);
|
|
177
|
+
candidates = candidates.filter((candidate) => !candidate.claim_provenance?.valid_until || parseTimestamp(candidate.claim_provenance.valid_until) >= evaluatedAt.getTime());
|
|
178
|
+
if (candidates.length === 0)
|
|
179
|
+
return refusal(EFFECTIVE_CAPABILITY_REFUSAL.requiredStale);
|
|
180
|
+
candidates = candidates.filter((candidate) => (request.limits ?? []).every((required) => {
|
|
181
|
+
const actual = candidate.limits?.[required.id];
|
|
182
|
+
if (!actual || actual.unit !== required.unit)
|
|
183
|
+
return false;
|
|
184
|
+
if (required.operator === "gte")
|
|
185
|
+
return actual.value >= required.value;
|
|
186
|
+
if (required.operator === "lte")
|
|
187
|
+
return actual.value <= required.value;
|
|
188
|
+
return required.operator === "eq" && actual.value === required.value;
|
|
189
|
+
}));
|
|
190
|
+
if (candidates.length === 0)
|
|
191
|
+
return refusal(EFFECTIVE_CAPABILITY_REFUSAL.limitUnsatisfied);
|
|
192
|
+
const preferenceUnavailable = (request.prefers ?? []).some((preferred) => !vocabulary[preferred.class]?.includes(preferred.id)
|
|
193
|
+
|| !candidates.some((candidate) => values(candidate, preferred.class)?.includes(preferred.id)));
|
|
194
|
+
return {
|
|
195
|
+
eligible: true,
|
|
196
|
+
variant_ids: candidates.map((candidate) => candidate.variant_id),
|
|
197
|
+
preference_unavailable: preferenceUnavailable,
|
|
198
|
+
preserved_extensions: [...new Set(candidates.flatMap((candidate) => Object.keys(candidate.extensions ?? {})))].sort(),
|
|
199
|
+
};
|
|
200
|
+
}
|
package/dist/iicpConsumer.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type CxPublicKey } from "./cxConfidentiality.js";
|
|
2
|
+
import { type RuntimeIdentityOptions } from "./runtimeIdentity.js";
|
|
2
3
|
export declare const DEFAULT_DIRECTORY_URL = "https://iicp.network";
|
|
3
4
|
export interface ClientConfig {
|
|
4
5
|
/** Directory base URL. Default: https://iicp.network (CORS-enabled). */
|
|
@@ -56,9 +57,19 @@ export interface Node {
|
|
|
56
57
|
[k: string]: unknown;
|
|
57
58
|
}
|
|
58
59
|
export interface ChatMessage {
|
|
59
|
-
role: "system" | "user" | "assistant";
|
|
60
|
+
role: "system" | "developer" | "user" | "assistant";
|
|
60
61
|
content: string;
|
|
61
62
|
}
|
|
63
|
+
export interface BrowserChatOptions {
|
|
64
|
+
endpoint: string;
|
|
65
|
+
intent?: string;
|
|
66
|
+
model?: string;
|
|
67
|
+
cxPublicKey?: CxPublicKey | null;
|
|
68
|
+
node?: Node;
|
|
69
|
+
allowed_regions?: string[];
|
|
70
|
+
required_manifest_identity_level?: RequiredManifestIdentityLevel | null;
|
|
71
|
+
runtime_identity?: RuntimeIdentityOptions;
|
|
72
|
+
}
|
|
62
73
|
/**
|
|
63
74
|
* Compatibility helper for callers that need to inspect or test the canonical
|
|
64
75
|
* plaintext task shape. Production `chat()` remains fail-closed and sends only
|
|
@@ -159,13 +170,13 @@ export declare function createRedactedRoutingReceipt(args: {
|
|
|
159
170
|
allowedRegions?: readonly string[] | null;
|
|
160
171
|
requiredManifestIdentityLevel?: RequiredManifestIdentityLevel | null;
|
|
161
172
|
}): RoutingReceipt;
|
|
162
|
-
/** Browser-native, consumer-only IICP client. */
|
|
163
173
|
export declare class IicpBrowserClient {
|
|
164
174
|
private readonly directory;
|
|
165
175
|
private readonly timeout;
|
|
166
176
|
private readonly allowedRegions;
|
|
167
177
|
private readonly requiredManifestIdentityLevel?;
|
|
168
178
|
private readonly routeDiscoveryMode;
|
|
179
|
+
private dispatchTicketKey?;
|
|
169
180
|
constructor(cfg?: ClientConfig);
|
|
170
181
|
private effectiveAllowedRegions;
|
|
171
182
|
private effectiveManifestIdentityLevel;
|
|
@@ -196,28 +207,12 @@ export declare class IicpBrowserClient {
|
|
|
196
207
|
* CORS, nor an IPv6-firewalled node (today's live nodes are `ipv6_direct_firewall_required`).
|
|
197
208
|
* Pass a reachable `endpoint`. In Node there is no CORS restriction. Returns the node JSON.
|
|
198
209
|
*/
|
|
199
|
-
chat(messages: ChatMessage[], opts:
|
|
200
|
-
endpoint: string;
|
|
201
|
-
intent?: string;
|
|
202
|
-
model?: string;
|
|
203
|
-
cxPublicKey?: CxPublicKey | null;
|
|
204
|
-
node?: Node;
|
|
205
|
-
allowed_regions?: string[];
|
|
206
|
-
required_manifest_identity_level?: RequiredManifestIdentityLevel | null;
|
|
207
|
-
}): Promise<Record<string, unknown>>;
|
|
210
|
+
chat(messages: ChatMessage[], opts: BrowserChatOptions): Promise<Record<string, unknown>>;
|
|
208
211
|
/**
|
|
209
212
|
* Same dispatch as `chat()`, but returns a redacted routing receipt. The receipt
|
|
210
213
|
* deliberately excludes prompt text, response text, node tokens and endpoint URLs.
|
|
211
214
|
*/
|
|
212
|
-
chatWithReceipt(messages: ChatMessage[], opts: {
|
|
213
|
-
endpoint: string;
|
|
214
|
-
intent?: string;
|
|
215
|
-
model?: string;
|
|
216
|
-
cxPublicKey?: CxPublicKey | null;
|
|
217
|
-
node?: Node;
|
|
218
|
-
allowed_regions?: string[];
|
|
219
|
-
required_manifest_identity_level?: RequiredManifestIdentityLevel | null;
|
|
220
|
-
}): Promise<{
|
|
215
|
+
chatWithReceipt(messages: ChatMessage[], opts: BrowserChatOptions): Promise<{
|
|
221
216
|
response: Record<string, unknown>;
|
|
222
217
|
receipt: RoutingReceipt;
|
|
223
218
|
}>;
|
package/dist/iicpConsumer.js
CHANGED
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
//
|
|
17
17
|
// Epic: #446 · Dev: #447 · Research: research/wasm/WASM-1-feasibility.md (#292).
|
|
18
18
|
import { encryptPayload } from "./cxConfidentiality.js";
|
|
19
|
+
import { verifyDispatchTicket } from "./dispatchTicket.js";
|
|
20
|
+
import { composeRuntimeIdentity, withRuntimeFacts } from "./runtimeIdentity.js";
|
|
21
|
+
import { BROWSER_NODE_VERSION } from "./version.js";
|
|
19
22
|
const REFUSED_INTENT_RULES = [
|
|
20
23
|
{ category: "prohibited", rule_id: "eu-ai-act-social-scoring", label: "social scoring", fragments: ["social-scoring", "social_scoring", "social:scoring"] },
|
|
21
24
|
{ category: "prohibited", rule_id: "eu-ai-act-criminal-risk", label: "individual criminal risk prediction", fragments: ["criminal-risk", "criminal_risk", "criminal:risk", "predict-crime"] },
|
|
@@ -271,12 +274,48 @@ export function createRedactedRoutingReceipt(args) {
|
|
|
271
274
|
};
|
|
272
275
|
}
|
|
273
276
|
/** Browser-native, consumer-only IICP client. */
|
|
277
|
+
function selectedAdvertisedModel(node, requestedModel) {
|
|
278
|
+
if (requestedModel && node?.models?.includes(requestedModel))
|
|
279
|
+
return requestedModel;
|
|
280
|
+
return node?.models?.length === 1 ? node.models[0] : undefined;
|
|
281
|
+
}
|
|
282
|
+
function effectiveCapabilityLabels(node, intent, model) {
|
|
283
|
+
const raw = node?.capabilities;
|
|
284
|
+
if (!Array.isArray(raw))
|
|
285
|
+
return [];
|
|
286
|
+
const variants = raw.filter((candidate) => Boolean(candidate) && typeof candidate === "object" && candidate.intent === intent);
|
|
287
|
+
const exact = model
|
|
288
|
+
? variants.filter((candidate) => Array.isArray(candidate.models) && candidate.models.includes(model))
|
|
289
|
+
: variants;
|
|
290
|
+
const selected = exact.length === 1 ? exact[0] : variants.length === 1 ? variants[0] : undefined;
|
|
291
|
+
if (!selected)
|
|
292
|
+
return [];
|
|
293
|
+
const labels = [];
|
|
294
|
+
for (const value of Array.isArray(selected.input_modalities) ? selected.input_modalities : []) {
|
|
295
|
+
if (typeof value === "string")
|
|
296
|
+
labels.push(`input_modality:${value}`);
|
|
297
|
+
}
|
|
298
|
+
for (const value of Array.isArray(selected.output_modalities) ? selected.output_modalities : []) {
|
|
299
|
+
if (typeof value === "string")
|
|
300
|
+
labels.push(`output_modality:${value}`);
|
|
301
|
+
}
|
|
302
|
+
for (const value of Array.isArray(selected.features) ? selected.features : []) {
|
|
303
|
+
if (typeof value === "string")
|
|
304
|
+
labels.push(value);
|
|
305
|
+
}
|
|
306
|
+
for (const value of Array.isArray(selected.execution_capabilities) ? selected.execution_capabilities : []) {
|
|
307
|
+
if (typeof value === "string")
|
|
308
|
+
labels.push(`execution:${value}`);
|
|
309
|
+
}
|
|
310
|
+
return [...new Set(labels)].sort();
|
|
311
|
+
}
|
|
274
312
|
export class IicpBrowserClient {
|
|
275
313
|
directory;
|
|
276
314
|
timeout;
|
|
277
315
|
allowedRegions;
|
|
278
316
|
requiredManifestIdentityLevel;
|
|
279
317
|
routeDiscoveryMode;
|
|
318
|
+
dispatchTicketKey;
|
|
280
319
|
constructor(cfg = {}) {
|
|
281
320
|
this.directory = (cfg.directory_url ?? DEFAULT_DIRECTORY_URL).replace(/\/+$/, "");
|
|
282
321
|
this.timeout = cfg.timeout_ms ?? 10_000;
|
|
@@ -338,6 +377,23 @@ export class IicpBrowserClient {
|
|
|
338
377
|
if (!route || typeof body.node_id !== "string") {
|
|
339
378
|
throw new IicpError("ticketed route response is malformed", "ticket_malformed");
|
|
340
379
|
}
|
|
380
|
+
if (!this.dispatchTicketKey) {
|
|
381
|
+
const keyResponse = await fetch(`${this.directory}/api/v1/directory-key`, {
|
|
382
|
+
headers: { Accept: "application/json" },
|
|
383
|
+
signal: AbortSignal.timeout(this.timeout),
|
|
384
|
+
});
|
|
385
|
+
const keyBody = await keyResponse.json().catch(() => ({}));
|
|
386
|
+
if (keyResponse.status === 200 && typeof keyBody.public_key === "string") {
|
|
387
|
+
this.dispatchTicketKey = keyBody.public_key;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
const issuer = this.directory.replace(/\/api$/, "");
|
|
391
|
+
const claims = typeof body.ticket === "string" && this.dispatchTicketKey
|
|
392
|
+
? verifyDispatchTicket(body.ticket, this.dispatchTicketKey, issuer, body.node_id, intent)
|
|
393
|
+
: null;
|
|
394
|
+
if (!claims) {
|
|
395
|
+
throw new IicpError("directory returned an unverifiable dispatch ticket", "ticket_unverified");
|
|
396
|
+
}
|
|
341
397
|
const node = {
|
|
342
398
|
...route,
|
|
343
399
|
node_id: body.node_id,
|
|
@@ -424,6 +480,15 @@ export class IicpBrowserClient {
|
|
|
424
480
|
async chatWithReceipt(messages, opts) {
|
|
425
481
|
const intent = opts.intent ?? "urn:iicp:intent:llm:chat:v1";
|
|
426
482
|
validateIntent(intent);
|
|
483
|
+
const selectedModel = selectedAdvertisedModel(opts.node, opts.model);
|
|
484
|
+
messages = composeRuntimeIdentity(messages, intent, withRuntimeFacts(opts.runtime_identity, {
|
|
485
|
+
client_name: "@iicp/web-node",
|
|
486
|
+
client_version: BROWSER_NODE_VERSION,
|
|
487
|
+
connection_mode: "routed",
|
|
488
|
+
selected_model: selectedModel,
|
|
489
|
+
effective_capabilities: effectiveCapabilityLabels(opts.node, intent, selectedModel),
|
|
490
|
+
selection_reason: "matched_intent_and_constraints",
|
|
491
|
+
}));
|
|
427
492
|
const taskId = globalThis.crypto?.randomUUID?.() ?? `task-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
428
493
|
const payload = { messages, model: opts.model };
|
|
429
494
|
// IICP-CX S.16: encryption is MANDATORY (privacy-first #360) — no opt-out.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
export * from "./iicpConsumer.js";
|
|
2
|
+
export * from "./dispatchTicket.js";
|
|
2
3
|
export * from "./cxConfidentiality.js";
|
|
4
|
+
export * from "./effectiveCapability.js";
|
|
5
|
+
export * from "./runtimeIdentity.js";
|
|
3
6
|
export * from "./browserNodeProvider.js";
|
|
4
7
|
export * from "./webllmRuntime.js";
|
|
5
8
|
export * from "./version.js";
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
// the WebLLM runtime helpers. Discovery + consume work from any https:// page; serving
|
|
7
7
|
// needs a relay (see README). Parity with the Python/TS/Rust SDKs on the wire.
|
|
8
8
|
export * from "./iicpConsumer.js";
|
|
9
|
+
export * from "./dispatchTicket.js";
|
|
9
10
|
export * from "./cxConfidentiality.js";
|
|
11
|
+
export * from "./effectiveCapability.js";
|
|
12
|
+
export * from "./runtimeIdentity.js";
|
|
10
13
|
export * from "./browserNodeProvider.js";
|
|
11
14
|
export * from "./webllmRuntime.js";
|
|
12
15
|
export * from "./version.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ChatMessage } from "./iicpConsumer.js";
|
|
2
|
+
export declare const RUNTIME_IDENTITY_PROFILE_ID = "urn:iicp:profile:runtime-identity-context:v0";
|
|
3
|
+
export declare const RUNTIME_IDENTITY_MARKER = "IICP-RUNTIME-CONTEXT/1";
|
|
4
|
+
export declare const RUNTIME_IDENTITY_CHAT_INTENT = "urn:iicp:intent:llm:chat:v1";
|
|
5
|
+
export declare const RUNTIME_IDENTITY_MAX_BYTES = 2048;
|
|
6
|
+
export type RuntimeIdentityMode = "auto" | "disabled" | "explicit" | "required";
|
|
7
|
+
export type RuntimeIdentityInstructionChannel = "system" | "unsupported";
|
|
8
|
+
export type RuntimeIdentityConnectionMode = "routed" | "local_browser";
|
|
9
|
+
export type RuntimeIdentitySelectionReason = "matched_intent_and_constraints" | "explicit_model_match" | "fallback_after_unavailable_candidate" | "intentional_exploration" | "local_browser_execution";
|
|
10
|
+
export interface RuntimeIdentityOptions {
|
|
11
|
+
mode?: RuntimeIdentityMode;
|
|
12
|
+
instruction_channel?: RuntimeIdentityInstructionChannel;
|
|
13
|
+
selected_model?: string;
|
|
14
|
+
effective_capabilities?: string[];
|
|
15
|
+
selection_reason?: RuntimeIdentitySelectionReason;
|
|
16
|
+
client_name?: string;
|
|
17
|
+
client_version?: string;
|
|
18
|
+
connection_mode?: RuntimeIdentityConnectionMode;
|
|
19
|
+
}
|
|
20
|
+
export declare class RuntimeIdentityContextUnsupported extends Error {
|
|
21
|
+
constructor();
|
|
22
|
+
}
|
|
23
|
+
export declare function withRuntimeFacts(options: RuntimeIdentityOptions | undefined, facts: Required<Pick<RuntimeIdentityOptions, "client_name" | "client_version" | "connection_mode" | "selection_reason">> & Pick<RuntimeIdentityOptions, "selected_model" | "effective_capabilities">): RuntimeIdentityOptions;
|
|
24
|
+
export declare function renderRuntimeIdentity(intent: string, options: RuntimeIdentityOptions): string;
|
|
25
|
+
export declare function composeRuntimeIdentity(messages: readonly ChatMessage[], intent: string, options?: RuntimeIdentityOptions): ChatMessage[];
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
export const RUNTIME_IDENTITY_PROFILE_ID = "urn:iicp:profile:runtime-identity-context:v0";
|
|
2
|
+
export const RUNTIME_IDENTITY_MARKER = "IICP-RUNTIME-CONTEXT/1";
|
|
3
|
+
export const RUNTIME_IDENTITY_CHAT_INTENT = "urn:iicp:intent:llm:chat:v1";
|
|
4
|
+
export const RUNTIME_IDENTITY_MAX_BYTES = 2048;
|
|
5
|
+
const MAX_FACT_BYTES = 160;
|
|
6
|
+
const MAX_CAPABILITIES = 32;
|
|
7
|
+
const BASE_CAPSULE = "This request reached you through IICP, the Intent-based Inter-agent Communication Protocol. IICP discovers eligible services and routes requests. You are the selected model or service, not IICP. When asked about this connection, use only supplied runtime facts; do not guess missing facts.";
|
|
8
|
+
export class RuntimeIdentityContextUnsupported extends Error {
|
|
9
|
+
constructor() {
|
|
10
|
+
super("required_identity_context_unsupported");
|
|
11
|
+
this.name = "RuntimeIdentityContextUnsupported";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const selectionText = {
|
|
15
|
+
matched_intent_and_constraints: "This service matched the requested intent and constraints.",
|
|
16
|
+
explicit_model_match: "This service matched the requested model and constraints.",
|
|
17
|
+
fallback_after_unavailable_candidate: "This service was selected after an earlier candidate was unavailable.",
|
|
18
|
+
intentional_exploration: "This service was selected for an intentional routing exploration.",
|
|
19
|
+
local_browser_execution: "This model is running locally in the browser.",
|
|
20
|
+
};
|
|
21
|
+
export function withRuntimeFacts(options, facts) {
|
|
22
|
+
return {
|
|
23
|
+
...(options ?? {}),
|
|
24
|
+
...facts,
|
|
25
|
+
selected_model: facts.selected_model,
|
|
26
|
+
effective_capabilities: [...(facts.effective_capabilities ?? [])],
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function boundedFact(value, name) {
|
|
30
|
+
if (!value || /[\u0000-\u001f\u007f]/u.test(value)) {
|
|
31
|
+
throw new Error(`runtime identity ${name} contains control characters`);
|
|
32
|
+
}
|
|
33
|
+
if (new TextEncoder().encode(value).byteLength > MAX_FACT_BYTES) {
|
|
34
|
+
throw new Error(`runtime identity ${name} exceeds the bounded fact limit`);
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
export function renderRuntimeIdentity(intent, options) {
|
|
39
|
+
const lines = [`[${RUNTIME_IDENTITY_MARKER}]`, BASE_CAPSULE, "Runtime facts:", `- intent: ${boundedFact(intent, "intent")}`];
|
|
40
|
+
if (options.client_name || options.client_version) {
|
|
41
|
+
if (!options.client_name || !options.client_version)
|
|
42
|
+
throw new Error("runtime identity client name and version must be supplied together");
|
|
43
|
+
lines.push(`- client: ${boundedFact(options.client_name, "client name")} ${boundedFact(options.client_version, "client version")}`);
|
|
44
|
+
}
|
|
45
|
+
if (options.connection_mode === "routed") {
|
|
46
|
+
lines.push("- connection: routed through IICP to an eligible provider.");
|
|
47
|
+
}
|
|
48
|
+
else if (options.connection_mode === "local_browser") {
|
|
49
|
+
lines.push("- connection: This model is running locally in the browser; no remote IICP provider was selected.");
|
|
50
|
+
}
|
|
51
|
+
else if (options.connection_mode !== undefined) {
|
|
52
|
+
throw new Error("runtime identity connection mode is unsupported");
|
|
53
|
+
}
|
|
54
|
+
if (options.selected_model)
|
|
55
|
+
lines.push(`- selected model: ${boundedFact(options.selected_model, "selected model")}`);
|
|
56
|
+
if ((options.effective_capabilities?.length ?? 0) > MAX_CAPABILITIES) {
|
|
57
|
+
throw new Error("runtime identity effective capabilities exceed the bounded count");
|
|
58
|
+
}
|
|
59
|
+
if (options.effective_capabilities?.length) {
|
|
60
|
+
lines.push(`- effective capabilities: ${options.effective_capabilities.map((value) => boundedFact(value, "effective capability")).join(", ")}`);
|
|
61
|
+
}
|
|
62
|
+
if (options.selection_reason) {
|
|
63
|
+
const selection = selectionText[options.selection_reason];
|
|
64
|
+
if (!selection)
|
|
65
|
+
throw new Error("runtime identity selection reason is unsupported");
|
|
66
|
+
lines.push(`- selection: ${selection}`);
|
|
67
|
+
}
|
|
68
|
+
const rendered = lines.join("\n");
|
|
69
|
+
if (new TextEncoder().encode(rendered).byteLength > RUNTIME_IDENTITY_MAX_BYTES) {
|
|
70
|
+
throw new Error("runtime identity context exceeds the 2048-byte limit");
|
|
71
|
+
}
|
|
72
|
+
return rendered;
|
|
73
|
+
}
|
|
74
|
+
export function composeRuntimeIdentity(messages, intent, options) {
|
|
75
|
+
const original = [...messages];
|
|
76
|
+
const resolved = options ?? {};
|
|
77
|
+
const mode = resolved.mode ?? "auto";
|
|
78
|
+
if (intent !== RUNTIME_IDENTITY_CHAT_INTENT)
|
|
79
|
+
return original;
|
|
80
|
+
if (!["auto", "disabled", "explicit", "required"].includes(mode)) {
|
|
81
|
+
throw new Error("runtime identity mode is unsupported");
|
|
82
|
+
}
|
|
83
|
+
if (mode === "disabled")
|
|
84
|
+
return original;
|
|
85
|
+
if (resolved.instruction_channel !== undefined
|
|
86
|
+
&& !["system", "unsupported"].includes(resolved.instruction_channel)) {
|
|
87
|
+
throw new Error("runtime identity instruction channel is unsupported");
|
|
88
|
+
}
|
|
89
|
+
if (resolved.instruction_channel === "unsupported") {
|
|
90
|
+
if (mode === "required")
|
|
91
|
+
throw new RuntimeIdentityContextUnsupported();
|
|
92
|
+
return original;
|
|
93
|
+
}
|
|
94
|
+
if (original.some((message) => (message.role === "system" || message.role === "developer")
|
|
95
|
+
&& message.content.includes(RUNTIME_IDENTITY_MARKER)))
|
|
96
|
+
return original;
|
|
97
|
+
let insertion = 0;
|
|
98
|
+
while (insertion < original.length && ["system", "developer"].includes(original[insertion].role))
|
|
99
|
+
insertion += 1;
|
|
100
|
+
return [
|
|
101
|
+
...original.slice(0, insertion),
|
|
102
|
+
{ role: "system", content: renderRuntimeIdentity(intent, resolved) },
|
|
103
|
+
...original.slice(insertion),
|
|
104
|
+
];
|
|
105
|
+
}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const BROWSER_NODE_VERSION = "0.2.
|
|
2
|
-
export declare const BROWSER_NODE_SDK_COMPATIBILITY_VERSION = "0.7.
|
|
1
|
+
export declare const BROWSER_NODE_VERSION = "0.2.5";
|
|
2
|
+
export declare const BROWSER_NODE_SDK_COMPATIBILITY_VERSION = "0.7.102";
|
|
3
3
|
/** Backward-compatible registration value for directories that know only sdk_version. */
|
|
4
|
-
export declare const BROWSER_NODE_SDK_VERSION = "0.7.
|
|
4
|
+
export declare const BROWSER_NODE_SDK_VERSION = "0.7.102";
|
package/dist/version.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Browser implementation and IICP SDK-compatibility versions are separate axes.
|
|
2
2
|
// Keep package.json synchronized with BROWSER_NODE_VERSION; the quality gate
|
|
3
3
|
// rejects drift. SDK compatibility describes the registration contract only.
|
|
4
|
-
export const BROWSER_NODE_VERSION = "0.2.
|
|
5
|
-
export const BROWSER_NODE_SDK_COMPATIBILITY_VERSION = "0.7.
|
|
4
|
+
export const BROWSER_NODE_VERSION = "0.2.5";
|
|
5
|
+
export const BROWSER_NODE_SDK_COMPATIBILITY_VERSION = "0.7.102";
|
|
6
6
|
/** Backward-compatible registration value for directories that know only sdk_version. */
|
|
7
7
|
export const BROWSER_NODE_SDK_VERSION = BROWSER_NODE_SDK_COMPATIBILITY_VERSION;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iicp/web-node",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Browser-native IICP node (consume + serve): discovery-mesh client with mandatory E2E encryption (IICP-CX) + WebLLM provider. Zero-config, ESM.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|