twin3-sdk 0.2.12-pre-alpha → 0.2.14-pre-alpha

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/README.md CHANGED
@@ -60,7 +60,14 @@ Twin3 SDK organizes all distributed primitives into seven clean, composable laye
60
60
  | **L4 Shield** | `twin3.shield` | Differential tampering defense, prompt injection filtering, and authorization guardrails. | `scan_text` / `scan_envelope` (T0–T3), `IntelEngine` (T1), `Ensemble` (T4), `diff_plans` / `authorize_execution` (T5), `MemoryGuard` |
61
61
  | **L5 Matrix** | `twin3.matrix` | High-density vector space topological mapping and semantic cosine matching. | `DenseVector256`, `feature_distance`, `HumanMatrixSchema`, `EnterpriseMatrixSchema` |
62
62
  | **L6 Settlement** | `twin3.settlement` | Signed-receipt verification for HTTP 402 gates, with externally supplied chain-finality and replay controls. | `PaymentDemand`, `PaymentReceipt`, `X402SettlementEngine` |
63
- | **L7 Governance** | `twin3.governance` | Immutable evidence trail, appeals, advisory reputation federation, provisional arbitration helper. | `EvidenceTrail`, `open_appeal` / `resolve_appeal`, `export_reputation` / `import_reputation`, `ArbitrationEngine` (experimental), `DisputeCase` (experimental) |
63
+ | **L7 Governance** | `twin3.governance` | Immutable evidence trail, appeals, advisory reputation federation, provisional arbitration helper. | `EvidenceTrail` (experimental), `open_appeal` / `resolve_appeal`, `export_reputation` / `import_reputation`, `ArbitrationEngine` (experimental), `DisputeCase` (experimental) |
64
+
65
+ L1 also exposes a candidate discovery evidence API for xAgent ID and xHuman ID. It normalizes owner-supplied CDN/server visits and Google Search Console generative AI search exports, then returns separate visit and impression summaries and a display-ready view model. See [the L1 evidence contract and interface presentation guidance](docs/architecture/L1-DISCOVERY-VISIT-EVIDENCE.md). These APIs do not collect private logs or establish visitor identity on their own.
66
+
67
+ Python and Node support [explicit Matrix comparison profiles](docs/matrix-runtime-profiles.md),
68
+ including weighted/masked cosine and structured coverage results. Node constructor
69
+ coercions still differ; Node Inbox payment admission remains Python-only. Evidence
70
+ trail is experimental until an actual consumer supplies durable integration evidence.
64
71
 
65
72
  `(experimental)` marks a capability whose row in [`tests/capability-inventory.json`](tests/capability-inventory.json) is not yet `available`: it is importable today and its surface may still change. Everything unmarked is `available`. A name written `Class.method` is a method, not a module export. Every name in this table is checked against a real public export by [`tests/test_readme_capability_claims.py`](tests/test_readme_capability_claims.py).
66
73
 
@@ -70,12 +77,17 @@ Twin3 SDK organizes all distributed primitives into seven clean, composable laye
70
77
 
71
78
  The primitives in `twin3-sdk` are extracted from the `twin3-team/agent-id` Inbox line (PRs #615–#642, merged 2026-09-03 → 2026-09-05; spec: `docs/architecture/inbox-module-spec.md` in that repo). What each layer inherited:
72
79
 
80
+ The paths below describe historical source in the
81
+ [Agent ID repository](https://github.com/twin3-team/agent-id/tree/main/agent_id/inbox),
82
+ not the current SDK directory layout. See the [generated Node API reference](docs/node-api.md)
83
+ for the installed package's public declarations.
84
+
73
85
  * **Envelope, KYA handshake, counterparty ladder** — `agent_id/inbox/{envelope,kya,counterparty}.py`: canonical-JSON signed envelopes with `authority:"none"`, the mutual Ed25519 challenge that binds a declared identity to a key, and the G0→G3 attention ladder keyed on the counterparty rather than the request.
74
86
  * **Task inbox and state machine** — `agent_id/inbox/state.py`: intake gate, review gate, rate limits, stale expiry, hash-chained audit.
75
87
  * **Shield T0–T5** — `agent_id/inbox/{shield,intel,classifier,plandiff,corpus}.py`: deterministic layers, URL/domain/hash intelligence, the T4 ensemble, plan diffing, and the corpus that publishes error rates.
76
88
  * **Settlement policy** — `agent_id/inbox/payments.py`: owner policy, signed quotes and receipts behind HTTP 402.
77
89
  * **Governance** — `agent_id/inbox/governance.py`: appeals, pardons, advisory reputation federation.
78
- * **Canonical Matrix Core**: High-density 256-Byte vector topological clustering powering 140k natural human personality profiles and industrial tolerance matching.
90
+ * **Canonical Matrix Core**: 256-dimensional single-pair vector arithmetic and tolerance comparison. The SDK does not supply population clustering, a similarity index or a batch ranking engine.
79
91
 
80
92
  The 2026-09-05 sync also adds the **AI-era hardening** (mandatory T5, identity-cost tier caps, provenance-gated memory, rotation demotes, paid ≠ authorized). See `CHANGELOG.md`.
81
93
 
@@ -103,22 +115,22 @@ pip install -e /path/to/twin3-sdk
103
115
  * Any protocol or algorithm improvement in `twin3-sdk` is reflected in both applications in **0 milliseconds**.
104
116
 
105
117
  #### 2. Production Distribution
106
- `v0.2.12-pre-alpha` is the current release candidate: `0.2.12-pre-alpha` for npm and `0.2.12a0` for PyPI. Publication is pending. Consumers must pin the exact released version and lock its registry integrity; never use a mutable range for a cryptographic protocol dependency. This release stays pre-alpha. Marketplace or sales copy may offer it for evaluation; it is not a stable release, and the npm dist-tag is `next`, not `latest`.
118
+ `v0.2.14-pre-alpha` is the current release candidate: `0.2.14-pre-alpha` for npm and `0.2.14a0` for PyPI. Publication is pending. Consumers must pin the exact released version and lock its registry integrity; never use a mutable range for a cryptographic protocol dependency. This release stays pre-alpha. Marketplace or sales copy may offer it for evaluation; it is not a stable release, and the npm dist-tag is `next`, not `latest`.
107
119
 
108
120
  `package.json` `engines` sets Node.js to `>=18` and does not set an npm engine. Any npm that can install a tarball can consume the package. Packing this repository was checked with npm 10 or newer; the stricter npm version in the release runbook applies only to Trusted Publishing.
109
121
 
110
122
  After publication, install the exact released version from the registry:
111
123
 
112
124
  ```bash
113
- npm install twin3-sdk@0.2.12-pre-alpha
114
- pip install twin3-sdk==0.2.12a0
125
+ npm install twin3-sdk@0.2.14-pre-alpha
126
+ pip install twin3-sdk==0.2.14a0
115
127
  ```
116
128
 
117
129
  For local evaluation, you can also use the packed npm tarball. Do not install from a git URL or a version range:
118
130
 
119
131
  ```bash
120
132
  npm pack --ignore-scripts
121
- npm install ./twin3-sdk-0.2.12-pre-alpha.tgz
133
+ npm install ./twin3-sdk-0.2.14-pre-alpha.tgz
122
134
  ```
123
135
 
124
136
  ---
@@ -135,7 +147,7 @@ Agent ID consumes Twin3 SDK to execute the **5-Stage A2A Autonomous Commercial L
135
147
 
136
148
  ### 👤 Human ID (Personal Sovereignty Projection)
137
149
  Human ID consumes Twin3 SDK to empower natural individuals:
138
- 1. **140,000 Real Personality Assets**: Computes high-density personality matching via `twin3.matrix` without risking underlying database schemas.
150
+ 1. **Personality Assets**: Uses `twin3.matrix` for single-pair vector comparisons. Population indexing, ranking throughput and storage remain product responsibilities.
139
151
  2. **Passkey WebAuthn Login**: Binds biometric secure enclaves to decentralized keys via `twin3.trust`.
140
152
  3. **Paid Inbox**: Protects individual inboxes against spam using `twin3.comm` and the signed-receipt adapter ($5 paywall threshold); the application supplies chain verification and shared replay state.
141
153
  4. **Sovereign Card**: Renders non-custodial credentials using `twin3.discovery`.
package/index.d.ts CHANGED
@@ -1,3 +1,8 @@
1
+ export type JsonPrimitive = string | number | boolean | null;
2
+ export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
3
+ export interface JsonObject { [key: string]: JsonValue; }
4
+ export type CryptoKeyInput = string | Buffer | import("node:crypto").KeyObject;
5
+
1
6
  export declare const AGENT_CARD_SCHEMA: "twin3-discovery-agent-card-v1";
2
7
  export declare const SOVEREIGN_CARD_SCHEMA: "twin3-discovery-sovereign-card-v1";
3
8
 
@@ -10,7 +15,7 @@ export interface Twin3AgentCard {
10
15
  public_key: string | null;
11
16
  capabilities: string[];
12
17
  endpoints: Record<string, string>;
13
- pricing: Record<string, any>;
18
+ pricing: JsonObject;
14
19
  created_at: number;
15
20
  digest: string;
16
21
  }
@@ -59,7 +64,7 @@ export interface Twin3AgentCardInput {
59
64
  publicKey?: string | null;
60
65
  capabilities?: string[];
61
66
  endpoints?: Record<string, string>;
62
- pricing?: Record<string, any>;
67
+ pricing?: JsonObject;
63
68
  createdAt?: number;
64
69
  }
65
70
 
@@ -72,15 +77,92 @@ export declare function createTwin3AgentCard(input: Twin3AgentCardInput): Twin3A
72
77
  export declare const createAgentCard: typeof createTwin3AgentCard;
73
78
  export declare function parseTwin3AgentCard(data: unknown, options?: { verify?: boolean }): Twin3AgentCard;
74
79
  export declare function parseSovereignCard(data: unknown, options?: { verify?: boolean }): SovereignCard;
75
- export declare function cardDigest(card: SovereignCard | Twin3AgentCard | Record<string, any>): string;
76
- export declare function verifyCardDigest(card: SovereignCard | Twin3AgentCard | Record<string, any>): string;
77
- export declare function inspectCardWire(card: SovereignCard | Twin3AgentCard | Record<string, any>): CardWireInspection;
78
- export declare function migrateCardToEmit(card: SovereignCard | Twin3AgentCard | Record<string, any>): SovereignCard | Twin3AgentCard;
80
+ export declare function cardDigest(card: SovereignCard | Twin3AgentCard | JsonObject): string;
81
+ export declare function verifyCardDigest(card: SovereignCard | Twin3AgentCard | JsonObject): string;
82
+ export declare function inspectCardWire(card: SovereignCard | Twin3AgentCard | JsonObject, options?: { allowLegacy?: boolean }): CardWireInspection;
83
+ export declare function migrateCardToEmit(card: SovereignCard | Twin3AgentCard | JsonObject): SovereignCard | Twin3AgentCard;
84
+
85
+ export declare const VISIT_EVIDENCE_SCHEMA: "twin3-discovery-visit-evidence-v1";
86
+ export declare const AI_EXPOSURE_SCHEMA: "twin3-discovery-ai-exposure-v1";
87
+ export declare const DISCOVERY_SUMMARY_SCHEMA: "twin3-discovery-evidence-summary-v1";
88
+ export declare const DISCOVERY_VIEW_SCHEMA: "twin3-discovery-evidence-view-v1";
89
+ export declare class DiscoveryEvidenceError extends Error { code: string; }
90
+ export interface DiscoveryVisitInput {
91
+ source: "cdn_log" | "server_log";
92
+ record_id: string;
93
+ source_digest: string;
94
+ observed_at: number;
95
+ path: string;
96
+ status: number;
97
+ method?: "GET" | "HEAD";
98
+ request_count?: number;
99
+ user_agent?: string;
100
+ host?: string;
101
+ }
102
+ export interface DiscoveryVisitEvidence {
103
+ schema: typeof VISIT_EVIDENCE_SCHEMA;
104
+ host: string;
105
+ path: string;
106
+ surface: "agent_card" | "website";
107
+ source: "cdn_log" | "server_log";
108
+ record_id: string;
109
+ source_digest: string;
110
+ observed_at: number;
111
+ request_count: number;
112
+ method: "GET" | "HEAD";
113
+ status: number;
114
+ provider: string | null;
115
+ bot: string | null;
116
+ evidence_level: "ua_claim" | "unclassified";
117
+ user_agent_digest: string;
118
+ digest: string;
119
+ }
120
+ export interface AiExposureInput {
121
+ source: "google_search_console_generative_ai_search";
122
+ report_digest: string;
123
+ date: string;
124
+ page: string;
125
+ impressions: number;
126
+ }
127
+ export interface AiExposureEvidence extends AiExposureInput {
128
+ schema: typeof AI_EXPOSURE_SCHEMA;
129
+ host: string;
130
+ /** SHA-256 of the complete canonical page URL, including query and fragment. */
131
+ page_digest: string;
132
+ evidence_level: "owner_supplied_platform_export";
133
+ digest: string;
134
+ }
135
+ export interface DiscoveryEvidenceSummary {
136
+ schema: typeof DISCOVERY_SUMMARY_SCHEMA;
137
+ host: string;
138
+ visits: { records: number; requests: number; successful: number; failed: number; agent_card_successful: number; agent_card_bot_claim_successful: number; by_bot_claim: Record<string, number>; by_path: Record<string, number>; by_day_utc: Record<string, number> };
139
+ google_ai_search: { records: number; impressions: number; by_date: Record<string, number> };
140
+ visit_digests: string[];
141
+ exposure_digests: string[];
142
+ digest: string;
143
+ }
144
+ export declare function normalizeDiscoveryVisit(row: DiscoveryVisitInput, options: { host: string }): DiscoveryVisitEvidence;
145
+ export declare function normalizeAiExposure(row: AiExposureInput, options: { host: string }): AiExposureEvidence;
146
+ export declare function summarizeDiscoveryEvidence(visits: DiscoveryVisitEvidence[], exposures: AiExposureEvidence[], options: { host: string }): DiscoveryEvidenceSummary;
147
+ export interface DiscoveryEvidenceView {
148
+ schema: typeof DISCOVERY_VIEW_SCHEMA;
149
+ host: string;
150
+ summary_digest: string;
151
+ cards: Array<{ id: string; label_zh_tw: string; value: number | null; unit: "requests" | "impressions"; state: "ready" | "not_connected" | "no_imported_records"; evidence_level: "http_log" | "ua_claim" | "owner_supplied_platform_export" }>;
152
+ trends: Array<{ id: string; unit: "requests" | "impressions"; date_basis: "utc" | "report_date"; state: "ready" | "not_connected" | "no_imported_records"; points: Array<{ date: string; value: number }> }>;
153
+ bot_claims: Array<{ bot: string; requests: number }>;
154
+ paths: Array<{ path: string; requests: number }>;
155
+ evidence_labels_zh_tw: Record<string, string>;
156
+ state_labels_zh_tw: Record<"no_imported_records" | "not_connected", string>;
157
+ notice_zh_tw: string;
158
+ digest: string;
159
+ }
160
+ export declare function buildDiscoveryEvidenceView(summary: DiscoveryEvidenceSummary, options: { visitSourceStatus: "connected" | "not_connected"; googleAiSearchSourceStatus: "connected" | "not_connected" }): DiscoveryEvidenceView;
79
161
 
80
162
  export declare const DESCRIPTOR_CANONICALIZATION: "rfc8785";
81
163
  export declare const DESCRIPTOR_SIGNATURE_FIELDS: readonly ["signatures", "signatureStatus"];
82
164
  export interface DescriptorSignature { protected: string; signature: string; }
83
- export interface SignedDescriptor extends Record<string, any> { signatures: DescriptorSignature[]; signatureStatus: string; }
165
+ export interface SignedDescriptor extends Record<string, unknown> { signatures: DescriptorSignature[]; signatureStatus: string; }
84
166
  export interface DescriptorVerification {
85
167
  status: "signed" | "unsigned";
86
168
  digest: string;
@@ -88,13 +170,13 @@ export interface DescriptorVerification {
88
170
  jku: string | null;
89
171
  protected: { alg: "EdDSA"; typ: string; kid: string; jku?: string } | null;
90
172
  }
91
- export declare function descriptorBody(document: Record<string, any>): Record<string, any>;
92
- export declare function descriptorBytes(document: Record<string, any>): Buffer;
93
- export declare function descriptorDigest(document: Record<string, any>): string;
94
- export declare function descriptorEtag(document: Record<string, any>): string;
95
- export declare function signDescriptor(document: Record<string, any>, privateKey: string | Buffer | import("node:crypto").KeyObject, options?: { kid?: string; jku?: string | null; typ?: string }): SignedDescriptor;
96
- export declare function unsignedDescriptor(document: Record<string, any>, reason?: string): SignedDescriptor;
97
- export declare function verifyDescriptor(document: Record<string, any>, publicKey: string | Buffer | import("node:crypto").KeyObject | null | undefined, options?: { expectedKid?: string | null; expectedJku?: string | null; allowUnsigned?: boolean }): DescriptorVerification;
173
+ export declare function descriptorBody(document: Record<string, unknown>): Record<string, unknown>;
174
+ export declare function descriptorBytes(document: Record<string, unknown>): Buffer;
175
+ export declare function descriptorDigest(document: Record<string, unknown>): string;
176
+ export declare function descriptorEtag(document: Record<string, unknown>): string;
177
+ export declare function signDescriptor(document: Record<string, unknown>, privateKey: string | Buffer | import("node:crypto").KeyObject, options?: { kid?: string; jku?: string | null; typ?: string }): SignedDescriptor;
178
+ export declare function unsignedDescriptor(document: Record<string, unknown>, reason?: string): SignedDescriptor;
179
+ export declare function verifyDescriptor(document: Record<string, unknown>, publicKey: string | Buffer | import("node:crypto").KeyObject | null | undefined, options?: { expectedKid?: string | null; expectedJku?: string | null; allowUnsigned?: boolean }): DescriptorVerification;
98
180
 
99
181
  export declare const WELL_KNOWN_DOCUMENT_SCHEMA: "twin3-discovery-well-known-v1";
100
182
  export interface WellKnownProtocol {
@@ -104,7 +186,7 @@ export interface WellKnownProtocol {
104
186
  required?: string[];
105
187
  implementation_specific?: string[];
106
188
  }
107
- export interface WellKnownDocument extends Record<string, any> {
189
+ export interface WellKnownDocument extends Record<string, unknown> {
108
190
  schema: string;
109
191
  host: string;
110
192
  did?: string;
@@ -112,8 +194,8 @@ export interface WellKnownDocument extends Record<string, any> {
112
194
  digest: string;
113
195
  }
114
196
  export declare function buildWellKnownDocument(host: string, protocol: WellKnownProtocol, fields: Record<string, any>, options?: { did?: boolean | string; schema?: string }): WellKnownDocument;
115
- export declare function validateWellKnownDocument(document: Record<string, any>): Required<WellKnownProtocol>;
116
- export declare function resolveDocumentPath(document: Record<string, any>, dotted: string): [boolean, any];
197
+ export declare function validateWellKnownDocument(document: Record<string, unknown>): Required<WellKnownProtocol>;
198
+ export declare function resolveDocumentPath(document: Record<string, unknown>, dotted: string): [boolean, unknown];
117
199
 
118
200
  export interface OwnerPolicyInput extends Record<string, any> {
119
201
  stranger_requires_payment?: unknown;
@@ -240,7 +322,7 @@ export interface CounterpartyTable {
240
322
  freeze(identity: CounterpartyIdentity, actor: string, reason: string, options?: { now?: number }): CounterpartyRow;
241
323
  unfreeze(identity: CounterpartyIdentity, actor: string, reason: string, options?: { now?: number }): CounterpartyRow;
242
324
  bindKey(identity: CounterpartyIdentity, binding: Record<string, any>, actor: string, reason: string,
243
- options?: { ownerPublicKey?: any; now?: number }): CounterpartyRow;
325
+ options?: { ownerPublicKey?: CryptoKeyInput; now?: number }): CounterpartyRow;
244
326
  boundKey(identity: CounterpartyIdentity): [string, string] | null;
245
327
  bindWallet(identity: CounterpartyIdentity, walletAddress: string,
246
328
  options?: { actor?: string; reason?: string; now?: number }): CounterpartyRow;
@@ -294,10 +376,10 @@ export declare function openAppeal(table: CounterpartyTable, identity: Counterpa
294
376
  export declare function resolveAppeal(table: CounterpartyTable, appealId: string,
295
377
  decision: "uphold" | "overturn", actor: string, reason: string, options?: { now?: number }): Appeal;
296
378
  export declare function listAppeals(table: CounterpartyTable, options?: { status?: string }): Appeal[];
297
- export declare function exportReputation(table: CounterpartyTable, owner: string, ownerPrivateKey: any,
379
+ export declare function exportReputation(table: CounterpartyTable, owner: string, ownerPrivateKey: CryptoKeyInput,
298
380
  options?: { now?: number; minStrikes?: number }): ReputationBundle;
299
381
  export declare function importReputation(table: CounterpartyTable, bundle: Record<string, any>,
300
- peerPublicKey: any, actor: string, options?: { now?: number; weight?: number }): ReputationImport;
382
+ peerPublicKey: CryptoKeyInput, actor: string, options?: { now?: number; weight?: number }): ReputationImport;
301
383
 
302
384
  export declare const TIERS: string[];
303
385
  export declare const TIER_RANK: Record<string, number>;
@@ -311,7 +393,7 @@ export declare function createCounterpartyTable(params: {
311
393
  store: Record<string, any>;
312
394
  owner: string;
313
395
  now?: number | (() => number);
314
- ownerPublicKey?: any;
396
+ ownerPublicKey?: CryptoKeyInput;
315
397
  legacyTierResolver?: (owner: string, key: string, snapshot: Record<string, any>) => string;
316
398
  }): CounterpartyTable;
317
399
  export declare function emptyCounterpartyStore(): { schema: string; owners: Record<string, any> };
@@ -330,13 +412,13 @@ export declare function issueOwnerAccessGrant(params: {
330
412
  grantEpoch: number;
331
413
  actor: string;
332
414
  reason: string;
333
- ownerPrivateKey: any;
415
+ ownerPrivateKey: CryptoKeyInput;
334
416
  now?: number;
335
417
  grantId?: string;
336
418
  }): OwnerAccessGrant;
337
419
  export declare function verifyOwnerAccessGrant(params: {
338
420
  grant: Record<string, any>;
339
- ownerPublicKey: any;
421
+ ownerPublicKey: CryptoKeyInput;
340
422
  owner: string;
341
423
  identity: CounterpartyIdentity;
342
424
  binding: Record<string, any>;
@@ -381,7 +463,7 @@ export interface A2AAgentCardSignature {
381
463
  header?: Record<string, unknown>;
382
464
  }
383
465
  export interface A2AJwks { keys: import("node:crypto").JsonWebKey[]; }
384
- export interface A2AAgentCard extends Record<string, any> {
466
+ export interface A2AAgentCard extends Record<string, unknown> {
385
467
  name: string;
386
468
  description: string;
387
469
  version: string;
@@ -486,7 +568,62 @@ export declare class DenseVector256 {
486
568
  cosineDistance(other: DenseVector256): number;
487
569
  compositeToleranceDistance(other: DenseVector256): number;
488
570
  matchTolerance(other: DenseVector256, maxDistance?: number): boolean;
489
- }
571
+ compare(other: DenseVector256, options?: MatrixComparisonOptions): MatrixComparisonResult;
572
+ }
573
+
574
+ export declare const COMPARISON_SCHEMA: "twin3-matrix-comparison-v1";
575
+ export declare const COMPARISON_PROFILE_SCHEMA: "twin3-matrix-comparison-profile-v1";
576
+ export type MatrixFeaturePolicy = "numeric" | "bitmask_jaccard" | "exact_bucket" | "split_nibble";
577
+ export interface MatrixComparisonOptions {
578
+ metric?: "cosine" | "composite_rms";
579
+ dimensionPolicies?: Record<number, MatrixFeaturePolicy>;
580
+ missingByte?: number | null;
581
+ weights?: number[] | null;
582
+ maxDistance?: number | null;
583
+ minCoverage?: number | null;
584
+ sourceDigest?: string | null;
585
+ projectionDigest?: string | null;
586
+ mappingReference?: string | null;
587
+ }
588
+ export interface MatrixComparisonProfileWire {
589
+ schema: typeof COMPARISON_PROFILE_SCHEMA;
590
+ layout: string;
591
+ registry_reference: string;
592
+ excluded_dimensions: number[];
593
+ unresolved_dimensions: number[];
594
+ }
595
+ export interface MatrixComparisonResult {
596
+ schema: typeof COMPARISON_SCHEMA;
597
+ status: "comparable" | "not_comparable" | "insufficient_coverage" | "metric_undefined";
598
+ reason: string | null;
599
+ distance: number | null;
600
+ match: boolean | null;
601
+ comparable_dimensions: number;
602
+ eligible_weight: number;
603
+ requested_weight: number;
604
+ coverage: number | null;
605
+ metric: "cosine" | "composite_rms";
606
+ policy_version: "l5-rms-v1";
607
+ source_digest: string | null;
608
+ projection_digest: string | null;
609
+ mapping_reference: string | null;
610
+ profile?: MatrixComparisonProfileWire;
611
+ }
612
+ export declare class ComparisonProfile {
613
+ readonly layout: string;
614
+ readonly registryReference: string;
615
+ readonly excluded: readonly number[];
616
+ readonly unresolved: readonly number[];
617
+ constructor(options: { layout: string; registryReference: string; excluded?: number[]; unresolved?: number[] });
618
+ comparableDimensions(): number[];
619
+ defaultWeights(): number[];
620
+ resolveWeights(weights?: number[] | null): number[];
621
+ assertLayout(aLayout: string, bLayout: string): void;
622
+ compare(a: DenseVector256, b: DenseVector256, options: MatrixComparisonOptions & { aLayout: string; bLayout: string }): MatrixComparisonResult;
623
+ toDict(): MatrixComparisonProfileWire;
624
+ }
625
+ export declare function humanComparisonProfile(registryReference: string, unresolved?: number[]): ComparisonProfile;
626
+ export declare function featureDistance(a: number, b: number, policy?: MatrixFeaturePolicy, missing?: number | null): number;
490
627
 
491
628
  export interface HumanMatrixQuadrantMap {
492
629
  physical: [number, number];
@@ -572,6 +709,41 @@ export declare function issuePasskeyChallenge(params: {
572
709
  expires_at: number;
573
710
  }>;
574
711
 
712
+ export interface PasskeyRegistrationInput {
713
+ challenge: string;
714
+ credentialId: string;
715
+ clientDataJson: string;
716
+ attestationObject: string;
717
+ expectedOrigin: string;
718
+ expectedRpId: string;
719
+ requireUserVerification?: boolean;
720
+ }
721
+ export interface PasskeyRegistrationResult {
722
+ readonly valid: true;
723
+ readonly credential_id: string;
724
+ readonly public_key_pem: string;
725
+ readonly algorithm: -7;
726
+ readonly rp_id: string;
727
+ readonly origin: string;
728
+ readonly sign_count: number;
729
+ readonly user_present: true;
730
+ readonly user_verified: boolean;
731
+ readonly backup_eligible: boolean;
732
+ readonly backup_state: boolean;
733
+ readonly attestation_format: "none";
734
+ }
735
+ export type PasskeyRegistrationErrorCode =
736
+ | "registration_input_invalid" | "registration_context_invalid"
737
+ | "registration_client_data_invalid" | "registration_challenge_mismatch"
738
+ | "registration_origin_mismatch" | "registration_attestation_invalid"
739
+ | "registration_rp_mismatch" | "registration_flags_invalid"
740
+ | "registration_credential_mismatch" | "registration_key_invalid";
741
+ export declare class PasskeyRegistrationError extends Error {
742
+ constructor(code?: PasskeyRegistrationErrorCode);
743
+ readonly code: PasskeyRegistrationErrorCode;
744
+ }
745
+ export declare function verifyPasskeyRegistration(input: PasskeyRegistrationInput): Readonly<PasskeyRegistrationResult>;
746
+
575
747
  export declare function verifyPasskeyAssertion(params: {
576
748
  challenge: string;
577
749
  clientDataJson: string;
@@ -640,7 +812,7 @@ export declare function verifyPasskeyAssertionWithStores(params: {
640
812
  challengeStore: ChallengeStore;
641
813
  }): Promise<ReturnType<typeof verifyPasskeyAssertion> & { user_id: string }>;
642
814
 
643
- export declare function keyId(publicKey: any): string;
815
+ export declare function keyId(publicKey: CryptoKeyInput): string;
644
816
 
645
817
  export interface KyaIdentity {
646
818
  kind: string;
@@ -684,7 +856,7 @@ export declare function createKyaChallenge(params: {
684
856
  now?: number;
685
857
  ttlSeconds?: number;
686
858
  }): KyaChallenge;
687
- export declare function verifyOwnerSignature(challenge: KyaChallenge, ownerPublicKey: any): true;
859
+ export declare function verifyOwnerSignature(challenge: KyaChallenge, ownerPublicKey: CryptoKeyInput): true;
688
860
  export declare function challengeSignaturePayload(challenge: KyaChallenge): Uint8Array;
689
861
  export declare function exportEd25519PublicKey(publicKey: string | object): string;
690
862
  export declare function verifyKyaChallenge(params: {
@@ -855,8 +1027,8 @@ export declare function buildEnvelope(params: {
855
1027
  ttlSeconds?: number;
856
1028
  }): Envelope;
857
1029
 
858
- export declare function signEnvelope(envelope: Envelope, privateKey: any): Envelope;
859
- export declare function verifyEnvelopeSignature(envelope: Envelope, publicKey: any, expectedKeyId?: string): true;
1030
+ export declare function signEnvelope(envelope: Envelope, privateKey: CryptoKeyInput): Envelope;
1031
+ export declare function verifyEnvelopeSignature(envelope: Envelope, publicKey: CryptoKeyInput, expectedKeyId?: string): true;
860
1032
 
861
1033
  export declare function scanText(text: string, options?: { source?: string; now?: number }): ShieldVerdict;
862
1034
 
@@ -1126,13 +1298,13 @@ export declare function issueReceipt(params: {
1126
1298
  identity: { kind: string; value: string };
1127
1299
  quote: Record<string, any>;
1128
1300
  reference: string;
1129
- ownerPrivateKey: any;
1301
+ ownerPrivateKey: CryptoKeyInput;
1130
1302
  now?: number;
1131
1303
  receiptId?: string;
1132
1304
  }): SettlementReceipt;
1133
1305
  export declare function verifyReceipt(params: {
1134
1306
  receipt: Record<string, any>;
1135
- ownerPublicKey: any;
1307
+ ownerPublicKey: CryptoKeyInput;
1136
1308
  owner: string;
1137
1309
  identity: { kind: string; value: string };
1138
1310
  quote?: Record<string, any> | null;
@@ -1292,7 +1464,7 @@ export interface CounterpartyAgent {
1292
1464
  keyId: string;
1293
1465
  routes: Record<"challenge" | "complete" | "submit" | "quote" | "declaration", string>;
1294
1466
  publicKey(format?: "compact" | "pem" | "multibase"): string;
1295
- answerChallenge(challenge: KyaChallenge, options?: { ownerPublicKey?: any; signPayload?: string }): ChallengeAnswer;
1467
+ answerChallenge(challenge: KyaChallenge, options?: { ownerPublicKey?: CryptoKeyInput; signPayload?: string }): ChallengeAnswer;
1296
1468
  buildEnvelope(kind: Envelope["kind"], payload: Record<string, any>, options?: { ttlSeconds?: number; now?: number }): Envelope;
1297
1469
  signEnvelope(envelope: Envelope): Envelope;
1298
1470
  envelope(kind: Envelope["kind"], payload: Record<string, any>, options?: { ttlSeconds?: number; now?: number }): Envelope;
@@ -1305,7 +1477,7 @@ export declare function createCounterpartyAgent(params: {
1305
1477
  identity: Identity;
1306
1478
  keyPath?: string;
1307
1479
  privateKeyPem?: string;
1308
- privateKey?: any;
1480
+ privateKey?: import("node:crypto").KeyObject;
1309
1481
  now?: () => number;
1310
1482
  legacySchemas?: boolean;
1311
1483
  routes?: Partial<CounterpartyAgent["routes"]>;
@@ -1320,8 +1492,8 @@ export declare function createRelayTransport(params: {
1320
1492
  export declare function createChallenge(params: {
1321
1493
  owner: string;
1322
1494
  identity: Identity;
1323
- counterpartyPublicKey: any;
1324
- ownerPrivateKey: any;
1495
+ counterpartyPublicKey: CryptoKeyInput;
1496
+ ownerPrivateKey: CryptoKeyInput;
1325
1497
  now?: number;
1326
1498
  ttlSeconds?: number;
1327
1499
  legacySchemas?: boolean;
@@ -1329,8 +1501,8 @@ export declare function createChallenge(params: {
1329
1501
 
1330
1502
  export declare function verifyChallengeAnswer(challenge: KyaChallenge, signature: string, options?: { now?: number }): true;
1331
1503
  export declare function envelopeDigest(envelope: Envelope): string;
1332
- export declare function loadPublicKey(value: any): any;
1333
- export declare function exportPublicKey(publicKey: any, format?: "compact" | "pem" | "multibase"): string;
1504
+ export declare function loadPublicKey(value: CryptoKeyInput): import("node:crypto").KeyObject;
1505
+ export declare function exportPublicKey(publicKey: CryptoKeyInput, format?: "compact" | "pem" | "multibase"): string;
1334
1506
  export declare const INBOX_ROUTES: CounterpartyAgent["routes"];
1335
1507
 
1336
1508
  export declare const TASK_STORE_SCHEMA: "twin3-comm-task-store-v1";
@@ -1523,3 +1695,27 @@ export declare namespace experimentalTaskInbox {
1523
1695
  expire(input: { principal: unknown; taskId: string; expectedVersion: number; operationId: string; reason: string }): Promise<InboxTask>;
1524
1696
  }
1525
1697
  }
1698
+
1699
+ export interface ExternalEd25519Signer {
1700
+ publicKey: string;
1701
+ sign(bytes: Uint8Array, signal: AbortSignal): Promise<string> | string;
1702
+ }
1703
+ export interface ExternalSignerOptions {
1704
+ now?: number;
1705
+ signal?: AbortSignal;
1706
+ timeoutMs?: number;
1707
+ }
1708
+ export type ExternalSignerErrorCode = "external_signer_input_invalid" | "external_signer_unavailable"
1709
+ | "external_signer_aborted" | "external_signer_timeout" | "external_signer_signature_invalid" | "external_signer_expired";
1710
+ export declare class ExternalSignerError extends Error {
1711
+ readonly code: ExternalSignerErrorCode;
1712
+ constructor(code: ExternalSignerErrorCode);
1713
+ }
1714
+ export declare function createKyaChallengeWithSigner(params: ExternalSignerOptions & {
1715
+ owner: string; identity: KyaIdentity; counterpartyPublicKey: string; signer: ExternalEd25519Signer;
1716
+ ttlSeconds?: number;
1717
+ }): Promise<Readonly<KyaChallenge>>;
1718
+ export declare function signDelegationWithSigner(delegation: Record<string, unknown>, signer: ExternalEd25519Signer,
1719
+ options?: ExternalSignerOptions): Promise<Readonly<Record<string, unknown>>>;
1720
+ export declare function signEnvelopeWithSigner(envelope: Envelope, signer: ExternalEd25519Signer,
1721
+ options?: ExternalSignerOptions): Promise<Readonly<Envelope>>;
@@ -345,7 +345,15 @@ function createRelayTransport({ serviceOrigin, accessToken, fetch: fetcher = glo
345
345
  const token = typeof accessToken === "function" ? await accessToken() : accessToken;
346
346
  const headers = { "content-type": "application/json" };
347
347
  if (token) headers.authorization = "Bearer " + token;
348
- const response = await fetcher(origin + pathname, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
348
+ const response = await fetcher(origin + pathname, {
349
+ method,
350
+ headers,
351
+ body: body === undefined ? undefined : JSON.stringify(body),
352
+ redirect: "manual",
353
+ });
354
+ if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
355
+ throw sdkError("inbox_redirect_forbidden");
356
+ }
349
357
  const payload = await response.json();
350
358
  if (!response.ok || payload.ok === false) {
351
359
  const error = sdkError(payload && payload.error ? payload.error : `inbox_http_${response.status}`);
package/js/comm.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ export {
2
+ ACCESS_GRANT_SCHEMA,
3
+ COUNTERPARTY_RECORD_SCHEMA,
4
+ COUNTERPARTY_STORE_SCHEMA,
5
+ ChallengeAnswer,
6
+ CounterpartyAgent,
7
+ CounterpartyAuditEntry,
8
+ CounterpartyIdentity,
9
+ CounterpartyRow,
10
+ CounterpartyTable,
11
+ CryptoKeyInput,
12
+ DEFAULT_RATE_LIMIT,
13
+ DEFAULT_RATE_WINDOW,
14
+ Envelope,
15
+ FREEZE_STRIKES,
16
+ INBOX_ROUTES,
17
+ Identity,
18
+ IdentityRequired,
19
+ InboxTransport,
20
+ IntakeRejected,
21
+ KyaChallenge,
22
+ KyaIdentity,
23
+ NONCE_RETENTION,
24
+ OwnerAccessGrant,
25
+ REPUTATION_HALF_LIFE_SECONDS,
26
+ STALE_AFTER,
27
+ STATES,
28
+ ShieldVerdict,
29
+ TASK_EXPORT_SCHEMA,
30
+ TASK_SCHEMA,
31
+ TASK_STORE_SCHEMA,
32
+ TERMINAL,
33
+ TIERS,
34
+ TIER_POLICY_VERSION,
35
+ TIER_RANK,
36
+ TRANSITIONS,
37
+ TaskInbox,
38
+ TaskInboxOptions,
39
+ TaskInboxTask,
40
+ TierTransitionError,
41
+ TransitionError,
42
+ buildEnvelope,
43
+ counterpartyKey,
44
+ createChallenge,
45
+ createCounterpartyAgent,
46
+ createCounterpartyTable,
47
+ createRelayTransport,
48
+ decayReputation,
49
+ emptyCounterpartyStore,
50
+ emptyTaskStore,
51
+ envelopeDigest,
52
+ experimentalTaskInbox,
53
+ exportPublicKey,
54
+ exportTask,
55
+ issueOwnerAccessGrant,
56
+ loadPublicKey,
57
+ maxTierFor,
58
+ normalizeCounterpartyStore,
59
+ normalizeTaskStore,
60
+ signEnvelope,
61
+ taskTrustLine,
62
+ verifyChallengeAnswer,
63
+ verifyEnvelopeSignature,
64
+ verifyOwnerAccessGrant,
65
+ verifyOwnerSignature,
66
+ } from "../index";
package/js/comm.js ADDED
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ const impl = require("./internal/comm.js");
3
+
4
+ module.exports = {
5
+ TaskInbox: impl.TaskInbox,
6
+ IntakeRejected: impl.IntakeRejected,
7
+ TransitionError: impl.TransitionError,
8
+ STATES: impl.STATES,
9
+ TRANSITIONS: impl.TRANSITIONS,
10
+ TERMINAL: impl.TERMINAL,
11
+ STALE_AFTER: impl.STALE_AFTER,
12
+ NONCE_RETENTION: impl.NONCE_RETENTION,
13
+ DEFAULT_RATE_LIMIT: impl.DEFAULT_RATE_LIMIT,
14
+ DEFAULT_RATE_WINDOW: impl.DEFAULT_RATE_WINDOW,
15
+ TASK_SCHEMA: impl.TASK_SCHEMA,
16
+ TASK_STORE_SCHEMA: impl.TASK_STORE_SCHEMA,
17
+ emptyTaskStore: impl.emptyTaskStore,
18
+ normalizeTaskStore: impl.normalizeTaskStore,
19
+ experimentalTaskInbox: impl.experimentalTaskInbox,
20
+ buildEnvelope: impl.buildEnvelope,
21
+ signEnvelope: impl.signEnvelope,
22
+ verifyEnvelopeSignature: impl.verifyEnvelopeSignature,
23
+ createCounterpartyAgent: impl.commCounterparty.createCounterpartyAgent,
24
+ createRelayTransport: impl.commCounterparty.createRelayTransport,
25
+ createChallenge: impl.commCounterparty.createChallenge,
26
+ verifyOwnerSignature: impl.commCounterparty.verifyOwnerSignature,
27
+ verifyChallengeAnswer: impl.commCounterparty.verifyChallengeAnswer,
28
+ envelopeDigest: impl.commCounterparty.envelopeDigest,
29
+ loadPublicKey: impl.commCounterparty.loadPublicKey,
30
+ exportPublicKey: impl.commCounterparty.exportPublicKey,
31
+ INBOX_ROUTES: impl.commCounterparty.ROUTES,
32
+ TASK_EXPORT_SCHEMA: impl.TASK_EXPORT_SCHEMA,
33
+ exportTask: impl.exportTask,
34
+ taskTrustLine: impl.taskTrustLine,
35
+ ACCESS_GRANT_SCHEMA: impl.ACCESS_GRANT_SCHEMA,
36
+ TIER_POLICY_VERSION: impl.TIER_POLICY_VERSION,
37
+ counterpartyKey: impl.counterpartyKey,
38
+ maxTierFor: impl.maxTierFor,
39
+ issueOwnerAccessGrant: impl.issueOwnerAccessGrant,
40
+ verifyOwnerAccessGrant: impl.verifyOwnerAccessGrant,
41
+ TIERS: impl.TIERS,
42
+ TIER_RANK: impl.TIER_RANK,
43
+ COUNTERPARTY_STORE_SCHEMA: impl.COUNTERPARTY_STORE_SCHEMA,
44
+ COUNTERPARTY_RECORD_SCHEMA: impl.COUNTERPARTY_RECORD_SCHEMA,
45
+ REPUTATION_HALF_LIFE_SECONDS: impl.REPUTATION_HALF_LIFE_SECONDS,
46
+ FREEZE_STRIKES: impl.FREEZE_STRIKES,
47
+ TierTransitionError: impl.TierTransitionError,
48
+ IdentityRequired: impl.IdentityRequired,
49
+ createCounterpartyTable: impl.createCounterpartyTable,
50
+ emptyCounterpartyStore: impl.emptyCounterpartyStore,
51
+ normalizeCounterpartyStore: impl.normalizeCounterpartyStore,
52
+ decayReputation: impl.decayReputation,
53
+ };