@greenlandai/sdk 0.5.11 → 0.5.13

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/CHANGELOG.md CHANGED
@@ -1,3 +1,18 @@
1
+ ## 0.5.13 (2026-09-30)
2
+ - **Zero-knowledge record envelope (ENYAL #6; RUL-0054/RUL-0055)** — the same change as @enyalai/sdk 2.2.11:
3
+ `crypto.decryptDisclosedChunk()` opens the `"ENYC" ‖ 0x01 ‖ r ‖ content` envelope of a record marked `hash_scheme:
4
+ "commit_v1"` and checks its commitment; unmarked records are unchanged. New: `crypto.decryptDisclosedRecord()`,
5
+ `crypto.openRecord()`, `crypto.verifyRecordOnDevice()`, `crypto.RecordIntegrityError`.
6
+ - **Removed: `client.gldai.mapdata()`** (operator 2026-09-30: "retire the SDK mapdata methods in this release. The route already
7
+ 404s"). GET /api/v1/mapdata was retired the same day (it answers 404); use map_viewport (mapViewport) for map reads.
8
+ - **Proof 409s.** ENYAL's uncharged refusals throw `ProofRefusedError` (a ConflictError; `.jouleCost 0`), not retried; the
9
+ idempotency "request in progress" 409 (Retry-After) is retried with the same key. Duplicates, `already_queued` and
10
+ `binding_note` documented on prove / proveBatch / queueProof.
11
+
12
+ ## 0.5.12 (2026-09-29)
13
+ - Version parity with the Python package (greenlandai 0.5.12). No JavaScript change: both fixes are in the Python
14
+ `EnyalAgent`; JavaScript users have them in @enyalai/sdk 2.2.10.
15
+
1
16
  ## 0.5.11 (2026-09-29)
2
17
  - Version parity with the Python package (greenlandai 0.5.11). No JavaScript change: the restore fix is in the Python
3
18
  `EnyalAgent`; JavaScript users have it in @enyalai/sdk 2.2.9.
package/README.md CHANGED
@@ -46,8 +46,24 @@ commodities, and the relationships between them (ownership, operation, supply).
46
46
  companies, deposits, infrastructure, projects, relationships (hops), look_from, nearby, map_viewport,
47
47
  look_at — are metered per call against the calling agent's own wallet; price any path first with
48
48
  billing_quote (free). Live totals: `GET https://greenlandai.ai/api/v1/public/stats` (public).
49
- `query` (natural language) and `mapdata` (bulk map layers) are **closed to all callers**; the methods
50
- still resolve but the server refuses them before any charge — use the structured reads and map_viewport.
49
+ `query` (natural language) is **closed to all callers**; the method still resolves but the server refuses it
50
+ before any charge — use the structured reads. The bulk map-layers route `/mapdata` was retired on 2026-09-30
51
+ (it answers 404) and its SDK method removed in 0.5.13 — use mapViewport for map reads.
52
+
53
+ ## ENYAL: zero-knowledge records, proof refusals and binding notes (0.5.13)
54
+
55
+ - **Zero-knowledge records.** A record archived by a zero-knowledge account after ENYAL's #6 change decrypts to
56
+ `"ENYC" ‖ 0x01 ‖ r ‖ content`; ENYAL keeps only its commitment `SHA-256(r ‖ content)` (`hash_scheme: "commit_v1"`).
57
+ `client.enyal.crypto.decryptDisclosedChunk()` opens it and checks the commitment; `decryptDisclosedRecord()` also returns
58
+ `r` (give it, with the content, to whoever you disclose the record to); `verifyRecordOnDevice()` is the on-device check
59
+ `/agreement/verify` cannot do for these records. A record that is not what was archived throws `RecordIntegrityError`
60
+ (`.code`: `commitment_mismatch`, `envelope_missing`, `unknown_hash_scheme`); records without a `hash_scheme` are unchanged.
61
+ - **Proof refusals.** ENYAL's uncharged 409 refusals (proofs over zero-knowledge records, `/agreement/verify` on one) throw
62
+ `ProofRefusedError` (a ConflictError; `.jouleCost` 0), not retried. The 409 sent while an earlier request with
63
+ the same idempotency key is still running carries a Retry-After; the SDK waits that long and retries with the same key.
64
+ - **Free replies and binding notes.** A proof ENYAL already made comes back free (`status: "already_proven"`,
65
+ `joule_cost: 0`); a queued one answers `status: "already_queued"`. Every PLONK proof carries `binding_note` (it binds the
66
+ first 31 of the 32 bytes of each record hash; quantumResistant binds all 32) — show it with the proof.
51
67
 
52
68
  ## Idempotency promise matrix (auto-retry behavior — design §6, post-G1 2026-06-10)
53
69
 
package/dist/index.cjs CHANGED
@@ -28,6 +28,7 @@ __export(js_exports, {
28
28
  NOT_SUPPORTED: () => NOT_SUPPORTED,
29
29
  NetworkError: () => NetworkError,
30
30
  NotFoundError: () => NotFoundError,
31
+ ProofRefusedError: () => ProofRefusedError,
31
32
  RateLimitError: () => RateLimitError,
32
33
  SAFE: () => SAFE,
33
34
  ScopeError: () => ScopeError,
@@ -59,6 +60,12 @@ var ValidationError = class extends GreenlandAIError {
59
60
  };
60
61
  var ConflictError = class extends GreenlandAIError {
61
62
  };
63
+ var ProofRefusedError = class extends ConflictError {
64
+ constructor(statusCode, detail, requestId = null) {
65
+ super(statusCode, detail, requestId);
66
+ this.jouleCost = 0;
67
+ }
68
+ };
62
69
  var RateLimitError = class extends GreenlandAIError {
63
70
  };
64
71
  var ServerError = class extends GreenlandAIError {
@@ -111,7 +118,6 @@ var IDEMPOTENCY_MAP = {
111
118
  "GET /api/v1/infrastructure": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
112
119
  "GET /api/v1/query": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
113
120
  "GET /api/v1/projects": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
114
- "GET /api/v1/mapdata": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
115
121
  // metered map/graph read surface (2026-09-14 SDK wrappers — parity with the MCP tools)
116
122
  "GET /api/v1/look.from": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
117
123
  "GET /api/v1/nearby": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
@@ -176,7 +182,17 @@ function parseRetryAfter(value) {
176
182
  const seconds = Number(value);
177
183
  return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
178
184
  }
185
+ var PROOF_REFUSAL_PATHS = /* @__PURE__ */ new Set([
186
+ "/api/v1/prove",
187
+ "/api/v1/prove-batch",
188
+ "/api/v1/compliance/attest",
189
+ "/api/v1/archive",
190
+ "/api/v1/proof/queue",
191
+ "/api/v1/disclose",
192
+ "/api/v1/agreement/verify"
193
+ ]);
179
194
  function isRetryable(err) {
195
+ if (err instanceof ConflictError && err.retryAfter != null) return true;
180
196
  return err instanceof NetworkError || err instanceof RateLimitError || err instanceof ServerError;
181
197
  }
182
198
  var noopLogger = { debug() {
@@ -253,7 +269,7 @@ var Transport = class {
253
269
  this._hist("sdk.request.duration", (Date.now() - t0) / 1e3);
254
270
  if (result && result.duplicate === true) {
255
271
  this._count("sdk.duplicates");
256
- this.logger.info(`duplicate response (idempotent replay) ${method} ${path}`);
272
+ this.logger.info(`duplicate response (nothing charged) ${method} ${path}`);
257
273
  }
258
274
  return result;
259
275
  } catch (err) {
@@ -262,6 +278,11 @@ var Transport = class {
262
278
  if (!retry || attempt >= maxRetries || !isRetryable(err) || raTooLong) {
263
279
  if (this.onTerminalFailure) this.onTerminalFailure(err, attempt + 1);
264
280
  this.logger.warn(`terminal failure ${method} ${path} after ${attempt + 1} attempt(s)`);
281
+ if (err.constructor === ConflictError && err.retryAfter == null && PROOF_REFUSAL_PATHS.has(pathTemplate)) {
282
+ const refused = new ProofRefusedError(err.statusCode, err.detail, err.requestId);
283
+ refused.cause = err;
284
+ throw refused;
285
+ }
265
286
  throw err;
266
287
  }
267
288
  let delay = Math.min(DEFAULT_INITIAL_DELAY * DEFAULT_BACKOFF_FACTOR ** attempt, DEFAULT_MAX_DELAY) + DEFAULT_JITTER_MIN + Math.random() * (DEFAULT_JITTER_MAX - DEFAULT_JITTER_MIN);
@@ -329,12 +350,18 @@ var Transport = class {
329
350
  // src/core/crypto.js
330
351
  var crypto_exports = {};
331
352
  __export(crypto_exports, {
353
+ HASH_SCHEME_COMMIT_V1: () => HASH_SCHEME_COMMIT_V1,
354
+ RecordIntegrityError: () => RecordIntegrityError,
355
+ ZK_ENVELOPE_MAGIC: () => ZK_ENVELOPE_MAGIC,
356
+ ZK_ENVELOPE_R_LEN: () => ZK_ENVELOPE_R_LEN,
357
+ ZK_ENVELOPE_V1: () => ZK_ENVELOPE_V1,
332
358
  bytesToHex: () => bytesToHex3,
333
359
  combineSharesAndDecrypt: () => combineSharesAndDecrypt,
334
360
  combineSharesAndDecryptHybrid: () => combineSharesAndDecryptHybrid,
335
361
  customerWrapKey: () => customerWrapKey,
336
362
  decryptCustodialShare: () => decryptCustodialShare,
337
363
  decryptDisclosedChunk: () => decryptDisclosedChunk,
364
+ decryptDisclosedRecord: () => decryptDisclosedRecord,
338
365
  decryptKnowledgeNode: () => decryptKnowledgeNode,
339
366
  decryptMessage: () => decryptMessage,
340
367
  deriveMlkemSeed: () => deriveMlkemSeed,
@@ -343,8 +370,10 @@ __export(crypto_exports, {
343
370
  hkdfSha256: () => hkdfSha256,
344
371
  hybridKDF: () => hybridKDF,
345
372
  mnemonicToCustomerShare: () => mnemonicToCustomerShare,
373
+ openRecord: () => openRecord,
346
374
  p256SharedSecretX: () => p256SharedSecretX,
347
375
  shamirCombine: () => shamirCombine,
376
+ verifyRecordOnDevice: () => verifyRecordOnDevice,
348
377
  verifyShareCombination: () => verifyShareCombination
349
378
  });
350
379
  var import_bip39 = require("@scure/bip39");
@@ -3639,11 +3668,82 @@ async function combineSharesAndDecryptHybrid(customerShare, custodialShare, chun
3639
3668
  const aesKey = await hybridKDF(ssEc, ssPq, ephemPub, mlkemCt);
3640
3669
  return aesGcmDecrypt(aesKey, iv, ct, tag);
3641
3670
  }
3642
- async function decryptDisclosedChunk(customerShare, custodialShare, chunk, p256ScalarMul) {
3671
+ var ZK_ENVELOPE_MAGIC = [69, 78, 89, 67];
3672
+ var ZK_ENVELOPE_V1 = 1;
3673
+ var ZK_ENVELOPE_R_LEN = 32;
3674
+ var HASH_SCHEME_COMMIT_V1 = "commit_v1";
3675
+ var RecordIntegrityError = class extends Error {
3676
+ constructor(code, message) {
3677
+ super(message);
3678
+ this.name = "RecordIntegrityError";
3679
+ this.code = code;
3680
+ }
3681
+ };
3682
+ async function sha256Hex(bytes) {
3683
+ return bytesToHex3(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
3684
+ }
3685
+ async function openRecord(bytes, chunk) {
3686
+ const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
3687
+ const scheme = chunk ? chunk.hash_scheme : void 0;
3688
+ const id = chunk && chunk.chunk_id || "";
3689
+ if (scheme === null || scheme === void 0) {
3690
+ return { content: data, r: null, hashScheme: null, commitment: null, commitmentMatches: null };
3691
+ }
3692
+ if (scheme !== HASH_SCHEME_COMMIT_V1) {
3693
+ throw new RecordIntegrityError(
3694
+ "unknown_hash_scheme",
3695
+ `Record ${id} uses hash_scheme ${JSON.stringify(scheme)}, which this SDK does not know \u2014 upgrade the SDK. Its bytes were not returned.`
3696
+ );
3697
+ }
3698
+ const head = ZK_ENVELOPE_MAGIC.length + 1;
3699
+ const isV1 = data.length >= head + ZK_ENVELOPE_R_LEN && ZK_ENVELOPE_MAGIC.every((b, i) => data[i] === b) && data[ZK_ENVELOPE_MAGIC.length] === ZK_ENVELOPE_V1;
3700
+ if (!isV1) {
3701
+ throw new RecordIntegrityError(
3702
+ "envelope_missing",
3703
+ `Record ${id} is marked commit_v1 but did not decrypt to an ENYC v1 envelope \u2014 it is not what was archived. Its bytes were not returned.`
3704
+ );
3705
+ }
3706
+ const r = data.slice(head, head + ZK_ENVELOPE_R_LEN);
3707
+ const content = data.slice(head + ZK_ENVELOPE_R_LEN);
3708
+ const commitment = String(chunk.commitment || chunk.chunk_hash || "").trim().toLowerCase();
3709
+ const buf = new Uint8Array(r.length + content.length);
3710
+ buf.set(r, 0);
3711
+ buf.set(content, r.length);
3712
+ if (!commitment || await sha256Hex(buf) !== commitment) {
3713
+ throw new RecordIntegrityError(
3714
+ "commitment_mismatch",
3715
+ `Record ${id}: SHA-256(r \u2016 content) does not match its commitment \u2014 the record or the commitment is not what was archived. Its bytes were not returned.`
3716
+ );
3717
+ }
3718
+ return { content, r, hashScheme: HASH_SCHEME_COMMIT_V1, commitment, commitmentMatches: true };
3719
+ }
3720
+ async function decryptDisclosedBytes(customerShare, custodialShare, chunk, p256ScalarMul) {
3643
3721
  const v = chunk.encryption_metadata && chunk.encryption_metadata.version;
3644
3722
  if (v === 6) return combineSharesAndDecryptHybrid(customerShare, custodialShare, chunk);
3645
3723
  return combineSharesAndDecrypt(customerShare, custodialShare, chunk, p256ScalarMul);
3646
3724
  }
3725
+ async function decryptDisclosedRecord(customerShare, custodialShare, chunk, p256ScalarMul) {
3726
+ return openRecord(await decryptDisclosedBytes(customerShare, custodialShare, chunk, p256ScalarMul), chunk);
3727
+ }
3728
+ async function decryptDisclosedChunk(customerShare, custodialShare, chunk, p256ScalarMul) {
3729
+ return (await decryptDisclosedRecord(customerShare, custodialShare, chunk, p256ScalarMul)).content;
3730
+ }
3731
+ async function verifyRecordOnDevice(record, terms) {
3732
+ const out = { commitmentMatches: record.commitmentMatches ?? null };
3733
+ if (terms !== void 0 && terms !== null) {
3734
+ const t = typeof terms === "string" ? new TextEncoder().encode(terms) : new Uint8Array(terms);
3735
+ const c = record.content;
3736
+ let match = !!c && t.length === c.length && t.every((b, i) => b === c[i]);
3737
+ if (match && record.r) {
3738
+ const buf = new Uint8Array(record.r.length + t.length);
3739
+ buf.set(record.r, 0);
3740
+ buf.set(t, record.r.length);
3741
+ match = await sha256Hex(buf) === record.commitment;
3742
+ }
3743
+ out.termsMatch = match;
3744
+ }
3745
+ return out;
3746
+ }
3647
3747
  async function verifyShareCombination(customerShare, custodialShare, poseidonKeyHash, wasmUrl) {
3648
3748
  const moduleUrl = wasmUrl || "/static/shamir_verify.js";
3649
3749
  const mod2 = await import(moduleUrl);
@@ -3782,7 +3882,7 @@ var EnyalSubmodule = class {
3782
3882
  if (title) body.title = title;
3783
3883
  return this._t.request(this._base, "POST", "/api/v1/agreement/create", { body, idempotencyKey, retry });
3784
3884
  }
3785
- /** ENFORCED (G1: trust_routes.py:453-471). */
3885
+ /** ENFORCED (G1: trust_routes.py:453-471). A period covering zero-knowledge records throws ProofRefusedError (409, nothing charged). */
3786
3886
  complianceAttest({ periodStart, periodEnd, systems, idempotencyKey, retry = true }) {
3787
3887
  return this._t.request(
3788
3888
  this._base,
@@ -3794,6 +3894,10 @@ var EnyalSubmodule = class {
3794
3894
  // ── class B (ENFORCED) ──
3795
3895
  /** 2.1.0: enyal-client.js:472. ENFORCED (prove_routes.py:204).
3796
3896
  * Filter queries: A proof paid for and not delivered is refunded in the same call: the response carries `refunded_joules` (refunds already sent back to your wallet) and `joule_cost` = the price minus it; a refund still in flight completes automatically and is not counted. A failure after the charge is an error and is refunded in full. */
3897
+ /* Replies you may get instead of a new proof (none charges): a stored proof of the same type over the same records comes
3898
+ * back free (status "already_proven", duplicate true, joule_cost 0); a proof of that record already queued answers status
3899
+ * "already_queued". A PLONK proof carries binding_note — what it binds (the first 31 of the 32 bytes of each record hash;
3900
+ * quantumResistant binds all 32); show it with the proof. Zero-knowledge records: ProofRefusedError (409, nothing charged). */
3797
3901
  prove({
3798
3902
  resourceType,
3799
3903
  geographicRegion,
@@ -3917,6 +4021,9 @@ var EnyalSubmodule = class {
3917
4021
  search({ idempotencyKey, retry = true, ...params } = {}) {
3918
4022
  return this._t.request(this._base, "GET", "/api/v1/search", { params, idempotencyKey, retry });
3919
4023
  }
4024
+ /** A zero-knowledge record (hash_scheme "commit_v1") cannot be verified by ENYAL — it holds only the commitment — and throws
4025
+ * ProofRefusedError (409, nothing charged): decrypt it with crypto.decryptDisclosedRecord and check it with
4026
+ * crypto.verifyRecordOnDevice. */
3920
4027
  verifyAgreement({ agreementChunkId, terms }) {
3921
4028
  return this._t.request(
3922
4029
  this._base,
@@ -3977,7 +4084,8 @@ var EnyalSubmodule = class {
3977
4084
  memoryContentQuery(body = {}, { idempotencyKey, retry = true } = {}) {
3978
4085
  return this._t.request(this._base, "POST", "/api/v1/memory/content-query", { body, idempotencyKey, retry });
3979
4086
  }
3980
- /** NOT retry-safe (archive_routes.py:440). */
4087
+ /** Queue a proof of one record. A record already queued answers status "already_queued" (free); a zero-knowledge record
4088
+ * throws ProofRefusedError (409, nothing charged). Auto-retry off. */
3981
4089
  queueProof(chunkId, quantumResistant = false) {
3982
4090
  return this._t.request(
3983
4091
  this._base,
@@ -4065,17 +4173,11 @@ var GldaiSubmodule = class {
4065
4173
  project(projectId) {
4066
4174
  return this._t.request(this._base, "GET", "/api/v1/projects/{pid}", { pathParams: { pid: projectId } });
4067
4175
  }
4068
- /** CLOSED — do NOT call. GET /api/v1/mapdata (the bulk map-layers surface) is closed to all callers and
4069
- * returns an error. Use mapViewport() for map reads. Kept only so the method still resolves for older
4070
- * callers. Matches the MCP `mapdata` tool (also marked CLOSED). */
4071
- mapdata({ idempotencyKey, ...params } = {}) {
4072
- return this._t.request(this._base, "GET", "/api/v1/mapdata", { params, idempotencyKey });
4073
- }
4074
4176
  // ── pricing + live map/graph read surface (2026-09-14; parity with the MCP tools) ──
4075
4177
  /** The exact per-caller price of a metered call BEFORE you make it — GET /api/v1/billing/quote. FREE
4076
4178
  * (no charge), needs only a credential (no verification). `path` = the API path the call would hit
4077
- * (e.g. "/api/v1/relationships", "/api/v1/look.from", "/api/v1/nearby", "/api/v1/companies/{id}",
4078
- * "/api/v1/mapdata"); `hops` = graph depth 1-10 (your tier caps it — Pioneer/FC 3, TEN/Pro 5,
4179
+ * (e.g. "/api/v1/relationships", "/api/v1/look.from", "/api/v1/nearby", "/api/v1/companies/{id}");
4180
+ * `hops` = graph depth 1-10 (your tier caps it — Pioneer/FC 3, TEN/Pro 5,
4079
4181
  * Enterprise 10) for a relationships path. Priced at YOUR tier.
4080
4182
  * Returns { joules (base), rail_fee_joules, joules_all_in, pricing_tier, usd, … } — joules_all_in is
4081
4183
  * the TRUE debit (base + the 0.5% rail surcharge), so fund THAT, not the base. Same helper as the MCP
@@ -4146,8 +4248,8 @@ var GldaiSubmodule = class {
4146
4248
  * all four), energy (default false), includeCountryCentroids (default false). AGENT KEYS ONLY; metered
4147
4249
  * against the CALLING agent's wallet (quote with billingQuote); pins do NOT count against your entity
4148
4250
  * cap. Response: top-level charged_joules (= price.charged_joules; the price block stays as the breakdown) +
4149
- * the metering block (file header). Same as the MCP `map_viewport` tool. Use this — the old /mapdata bulk
4150
- * surface is CLOSED. */
4251
+ * the metering block (file header). Same as the MCP `map_viewport` tool. Use this (the old /mapdata bulk
4252
+ * route was retired 2026-09-30). */
4151
4253
  mapViewport({
4152
4254
  minLat,
4153
4255
  minLng,
@@ -4786,7 +4888,7 @@ var RareeaiSubmodule = class _RareeaiSubmodule {
4786
4888
  };
4787
4889
 
4788
4890
  // index.js
4789
- var VERSION = "0.5.11";
4891
+ var VERSION = "0.5.13";
4790
4892
  var Client = class {
4791
4893
  /**
4792
4894
  * @param {object} opts
@@ -4837,6 +4939,7 @@ var Client = class {
4837
4939
  NOT_SUPPORTED,
4838
4940
  NetworkError,
4839
4941
  NotFoundError,
4942
+ ProofRefusedError,
4840
4943
  RateLimitError,
4841
4944
  SAFE,
4842
4945
  ScopeError,
package/index.js CHANGED
@@ -11,12 +11,12 @@ import { GldaiSubmodule, GLDAI_BASE } from "./src/gldai.js";
11
11
 
12
12
  export {
13
13
  GreenlandAIError, AuthError, ScopeError, NotFoundError, ValidationError,
14
- ConflictError, RateLimitError, ServerError, NetworkError,
14
+ ConflictError, ProofRefusedError, RateLimitError, ServerError, NetworkError,
15
15
  } from "./src/core/errors.js";
16
16
  export { ENFORCED, NOT_SUPPORTED, SAFE, IDEMPOTENCY_MAP } from "./src/core/idempotency.js";
17
17
  export * as crypto from "./src/core/crypto.js";
18
18
 
19
- export const VERSION = "0.5.11";
19
+ export const VERSION = "0.5.13";
20
20
 
21
21
  export class Client {
22
22
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greenlandai/sdk",
3
- "version": "0.5.11",
3
+ "version": "0.5.13",
4
4
  "description": "Unified SDK for the GreenlandAI ecosystem (ENYAL, JoulePAI, RAREEAI, GreenlandAI)",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://greenlandai.ai",
@@ -311,13 +311,138 @@ export async function combineSharesAndDecryptHybrid(customerShare, custodialShar
311
311
  return aesGcmDecrypt(aesKey, iv, ct, tag);
312
312
  }
313
313
 
314
- /** Version-dispatch client-side decrypt: v6 -> hybrid, else (v5) -> classical. */
315
- export async function decryptDisclosedChunk(customerShare, custodialShare, chunk, p256ScalarMul) {
314
+ // ────────────────────────────────────────────────────────────────
315
+ // Zero-knowledge record envelope (ENYAL #6, RUL-0054 / RUL-0055)
316
+ // A zero-knowledge record archived after ENYAL's #6 change decrypts to
317
+ // "ENYC" ‖ 0x01 ‖ r (32 random bytes) ‖ content
318
+ // and ENYAL stores only its commitment, SHA-256(r ‖ content) (hash_scheme "commit_v1").
319
+ // Spec: docs/instrument-runs/p123-zk-commitment-client-spec-2026-09-30T0019Z.md.
320
+ // ────────────────────────────────────────────────────────────────
321
+
322
+ export const ZK_ENVELOPE_MAGIC = [0x45, 0x4e, 0x59, 0x43]; // "ENYC"
323
+ export const ZK_ENVELOPE_V1 = 1;
324
+ export const ZK_ENVELOPE_R_LEN = 32;
325
+ export const HASH_SCHEME_COMMIT_V1 = "commit_v1";
326
+
327
+ /**
328
+ * A decrypted record is not what ENYAL says was archived. err.code is one of:
329
+ * 'commitment_mismatch' — SHA-256(r ‖ content) differs from the record's commitment (or no commitment was supplied);
330
+ * 'envelope_missing' — the record is marked commit_v1 but the decrypted bytes are not an ENYC v1 envelope;
331
+ * 'unknown_hash_scheme' — the record names a hash_scheme this SDK does not know (fail closed; upgrade the SDK).
332
+ * The record's bytes are never returned.
333
+ */
334
+ export class RecordIntegrityError extends Error {
335
+ constructor(code, message) {
336
+ super(message);
337
+ this.name = "RecordIntegrityError";
338
+ this.code = code;
339
+ }
340
+ }
341
+
342
+ async function sha256Hex(bytes) {
343
+ return bytesToHex(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
344
+ }
345
+
346
+ /**
347
+ * Open a decrypted record according to its chunk metadata (the /disclose/client-side entry or an archive-history row).
348
+ * Resolves { content, r, hashScheme, commitment, commitmentMatches }:
349
+ * - hash_scheme null/absent (every record before ENYAL's #6 change, every recoverable account's, every message): the bytes
350
+ * come back UNCHANGED, even if they start with "ENYC" 0x01 — only the server's marker says a record has an envelope;
351
+ * r, commitment and commitmentMatches are null.
352
+ * - hash_scheme "commit_v1": the envelope is opened, SHA-256(r ‖ content) is compared with the record's commitment, and the
353
+ * CONTENT is returned with r (hand r to whoever you disclose the record to). A mismatch or a missing envelope throws
354
+ * RecordIntegrityError.
355
+ * - any other hash_scheme: RecordIntegrityError('unknown_hash_scheme').
356
+ * @param {Uint8Array} bytes - decrypted bytes
357
+ * @param {Object} chunk - chunk metadata (hash_scheme, commitment | chunk_hash)
358
+ */
359
+ export async function openRecord(bytes, chunk) {
360
+ const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
361
+ const scheme = chunk ? chunk.hash_scheme : undefined;
362
+ const id = (chunk && chunk.chunk_id) || "";
363
+ if (scheme === null || scheme === undefined) {
364
+ return { content: data, r: null, hashScheme: null, commitment: null, commitmentMatches: null };
365
+ }
366
+ if (scheme !== HASH_SCHEME_COMMIT_V1) {
367
+ throw new RecordIntegrityError("unknown_hash_scheme",
368
+ `Record ${id} uses hash_scheme ${JSON.stringify(scheme)}, which this SDK does not know — upgrade the SDK. ` +
369
+ "Its bytes were not returned.");
370
+ }
371
+ const head = ZK_ENVELOPE_MAGIC.length + 1;
372
+ const isV1 = data.length >= head + ZK_ENVELOPE_R_LEN && ZK_ENVELOPE_MAGIC.every((b, i) => data[i] === b)
373
+ && data[ZK_ENVELOPE_MAGIC.length] === ZK_ENVELOPE_V1;
374
+ if (!isV1) {
375
+ throw new RecordIntegrityError("envelope_missing",
376
+ `Record ${id} is marked commit_v1 but did not decrypt to an ENYC v1 envelope — it is not what was archived. ` +
377
+ "Its bytes were not returned.");
378
+ }
379
+ const r = data.slice(head, head + ZK_ENVELOPE_R_LEN);
380
+ const content = data.slice(head + ZK_ENVELOPE_R_LEN);
381
+ // The value is chunk.commitment (disclose/client-side) or chunk.chunk_hash (an archive-history row) — never the
382
+ // descriptive string in chunk.envelope.commitment.
383
+ const commitment = String(chunk.commitment || chunk.chunk_hash || "").trim().toLowerCase();
384
+ const buf = new Uint8Array(r.length + content.length);
385
+ buf.set(r, 0); buf.set(content, r.length);
386
+ if (!commitment || (await sha256Hex(buf)) !== commitment) {
387
+ throw new RecordIntegrityError("commitment_mismatch",
388
+ `Record ${id}: SHA-256(r ‖ content) does not match its commitment — the record or the commitment is not what ` +
389
+ "was archived. Its bytes were not returned.");
390
+ }
391
+ return { content, r, hashScheme: HASH_SCHEME_COMMIT_V1, commitment, commitmentMatches: true };
392
+ }
393
+
394
+ async function decryptDisclosedBytes(customerShare, custodialShare, chunk, p256ScalarMul) {
316
395
  const v = chunk.encryption_metadata && chunk.encryption_metadata.version;
317
396
  if (v === 6) return combineSharesAndDecryptHybrid(customerShare, custodialShare, chunk);
318
397
  return combineSharesAndDecrypt(customerShare, custodialShare, chunk, p256ScalarMul);
319
398
  }
320
399
 
400
+ /**
401
+ * Decrypt a disclosed chunk (v6 PQ-hybrid or v5) and open it — see openRecord. Never resolves to envelope bytes; throws
402
+ * RecordIntegrityError when a zero-knowledge record's commitment does not match. Mirror of the Python decrypt_disclosed_record.
403
+ * @returns {Promise<{content: Uint8Array, r: Uint8Array|null, hashScheme: string|null, commitment: string|null, commitmentMatches: boolean|null}>}
404
+ */
405
+ export async function decryptDisclosedRecord(customerShare, custodialShare, chunk, p256ScalarMul) {
406
+ return openRecord(await decryptDisclosedBytes(customerShare, custodialShare, chunk, p256ScalarMul), chunk);
407
+ }
408
+
409
+ /**
410
+ * Version-dispatch client-side decrypt: v6 -> hybrid, else (v5) -> classical.
411
+ * v5 uses the built-in @noble P-256 provider by default (override via p256ScalarMul).
412
+ *
413
+ * 2.2.11: resolves to the record's CONTENT. A zero-knowledge record marked hash_scheme "commit_v1" is opened and its
414
+ * commitment checked (RecordIntegrityError on a mismatch); every other record's bytes come back unchanged. Use
415
+ * decryptDisclosedRecord to get r as well.
416
+ */
417
+ export async function decryptDisclosedChunk(customerShare, custodialShare, chunk, p256ScalarMul) {
418
+ return (await decryptDisclosedRecord(customerShare, custodialShare, chunk, p256ScalarMul)).content;
419
+ }
420
+
421
+ /**
422
+ * The on-device check for a record opened by decryptDisclosedRecord / openRecord — what ENYAL's /agreement/verify cannot do
423
+ * for a zero-knowledge record (it answers 409: it holds only the commitment, never r).
424
+ * Resolves { commitmentMatches, termsMatch? }: commitmentMatches is true for a checked commit_v1 record (a mismatch never gets
425
+ * this far — openRecord throws) and null for a record with no commitment; termsMatch (only when terms are given) is true when
426
+ * the terms equal the content byte for byte (a string is UTF-8 encoded) and, for a commit_v1 record, SHA-256(r ‖ terms)
427
+ * equals its commitment.
428
+ */
429
+ export async function verifyRecordOnDevice(record, terms) {
430
+ const out = { commitmentMatches: record.commitmentMatches ?? null };
431
+ if (terms !== undefined && terms !== null) {
432
+ const t = typeof terms === "string" ? new TextEncoder().encode(terms) : new Uint8Array(terms);
433
+ const c = record.content;
434
+ let match = !!c && t.length === c.length && t.every((b, i) => b === c[i]);
435
+ if (match && record.r) {
436
+ const buf = new Uint8Array(record.r.length + t.length);
437
+ buf.set(record.r, 0); buf.set(t, record.r.length);
438
+ match = (await sha256Hex(buf)) === record.commitment;
439
+ }
440
+ out.termsMatch = match;
441
+ }
442
+ return out;
443
+ }
444
+
445
+
321
446
  /**
322
447
  * 4. Verify share combination locally via WASM (78KB).
323
448
  * Runs content integrity hash of reconstructed key in browser — zero server calls.
@@ -15,6 +15,12 @@ export class ScopeError extends GreenlandAIError {}
15
15
  export class NotFoundError extends GreenlandAIError {}
16
16
  export class ValidationError extends GreenlandAIError {}
17
17
  export class ConflictError extends GreenlandAIError {}
18
+ /** 409 — ENYAL refused a proof or verification request BEFORE charging (proofs over zero-knowledge records, a SHA-256
19
+ * content proof on /disclose, /agreement/verify on a zero-knowledge record). Not retried; detail says what to change;
20
+ * jouleCost is 0. A ConflictError, so existing handlers still catch it. */
21
+ export class ProofRefusedError extends ConflictError {
22
+ constructor(statusCode, detail, requestId = null) { super(statusCode, detail, requestId); this.jouleCost = 0; }
23
+ }
18
24
  export class RateLimitError extends GreenlandAIError {}
19
25
  export class ServerError extends GreenlandAIError {}
20
26
  export class NetworkError extends GreenlandAIError {
@@ -38,7 +38,6 @@ export const IDEMPOTENCY_MAP = {
38
38
  "GET /api/v1/infrastructure": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
39
39
  "GET /api/v1/query": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
40
40
  "GET /api/v1/projects": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
41
- "GET /api/v1/mapdata": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
42
41
  // metered map/graph read surface (2026-09-14 SDK wrappers — parity with the MCP tools)
43
42
  "GET /api/v1/look.from": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
44
43
  "GET /api/v1/nearby": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
@@ -4,7 +4,7 @@
4
4
  * 3 retries, 500ms initial, 8s max, x2 backoff, 100-300ms jitter; retryable =
5
5
  * network/5xx/429; Retry-After honored. Layered rule: NOT_SUPPORTED tier => no auto-retry.
6
6
  */
7
- import { NetworkError, RateLimitError, ServerError, errorForStatus } from "./errors.js";
7
+ import { ConflictError, NetworkError, ProofRefusedError, RateLimitError, ServerError, errorForStatus } from "./errors.js";
8
8
  import { NOT_SUPPORTED, dispatch } from "./idempotency.js";
9
9
 
10
10
  const DEFAULT_MAX_RETRIES = 3;
@@ -37,7 +37,19 @@ function parseRetryAfter(value) {
37
37
  return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
38
38
  }
39
39
 
40
+ // Paths where ENYAL answers a request it will not serve with a 409 and NO charge (2026-09-30): a proof over zero-knowledge
41
+ // records (/prove, /prove-batch, /compliance/attest, /archive with proof_tier, /proof/queue), a SHA-256 content proof on
42
+ // /disclose, and /agreement/verify on a zero-knowledge record. ENYAL's idempotency "in progress" 409 on the same paths carries a
43
+ // Retry-After and is retried instead (it is never a ProofRefusedError).
44
+ const PROOF_REFUSAL_PATHS = new Set([
45
+ "/api/v1/prove", "/api/v1/prove-batch", "/api/v1/compliance/attest", "/api/v1/archive", "/api/v1/proof/queue",
46
+ "/api/v1/disclose", "/api/v1/agreement/verify",
47
+ ]);
48
+
40
49
  function isRetryable(err) {
50
+ // a 409 that carries a Retry-After is ENYAL's idempotency "request in progress" reply: retried with the same key after the
51
+ // time it names (a refusal carries none).
52
+ if (err instanceof ConflictError && err.retryAfter != null) return true;
41
53
  return err instanceof NetworkError || err instanceof RateLimitError || err instanceof ServerError;
42
54
  }
43
55
 
@@ -105,7 +117,8 @@ export class Transport {
105
117
  this._count("sdk.requests"); this._hist("sdk.request.duration", (Date.now() - t0) / 1000);
106
118
  if (result && result.duplicate === true) {
107
119
  this._count("sdk.duplicates");
108
- this.logger.info(`duplicate response (idempotent replay) ${method} ${path}`);
120
+ // an idempotent replay, or (ENYAL proofs) a stored/queued proof returned free — joule_cost 0 either way
121
+ this.logger.info(`duplicate response (nothing charged) ${method} ${path}`);
109
122
  }
110
123
  return result;
111
124
  } catch (err) {
@@ -114,6 +127,11 @@ export class Transport {
114
127
  if (!retry || attempt >= maxRetries || !isRetryable(err) || raTooLong) {
115
128
  if (this.onTerminalFailure) this.onTerminalFailure(err, attempt + 1);
116
129
  this.logger.warn(`terminal failure ${method} ${path} after ${attempt + 1} attempt(s)`);
130
+ if (err.constructor === ConflictError && err.retryAfter == null && PROOF_REFUSAL_PATHS.has(pathTemplate)) {
131
+ const refused = new ProofRefusedError(err.statusCode, err.detail, err.requestId);
132
+ refused.cause = err;
133
+ throw refused;
134
+ }
117
135
  throw err;
118
136
  }
119
137
  let delay = Math.min(DEFAULT_INITIAL_DELAY * DEFAULT_BACKOFF_FACTOR ** attempt, DEFAULT_MAX_DELAY)
package/src/enyal.js CHANGED
@@ -37,7 +37,7 @@ export class EnyalSubmodule {
37
37
  return this._t.request(this._base, "POST", "/api/v1/agreement/create", { body, idempotencyKey, retry });
38
38
  }
39
39
 
40
- /** ENFORCED (G1: trust_routes.py:453-471). */
40
+ /** ENFORCED (G1: trust_routes.py:453-471). A period covering zero-knowledge records throws ProofRefusedError (409, nothing charged). */
41
41
  complianceAttest({ periodStart, periodEnd, systems, idempotencyKey, retry = true }) {
42
42
  return this._t.request(this._base, "POST", "/api/v1/compliance/attest",
43
43
  { body: { period_start: periodStart, period_end: periodEnd, systems }, idempotencyKey, retry });
@@ -46,6 +46,10 @@ export class EnyalSubmodule {
46
46
  // ── class B (ENFORCED) ──
47
47
  /** 2.1.0: enyal-client.js:472. ENFORCED (prove_routes.py:204).
48
48
  * Filter queries: A proof paid for and not delivered is refunded in the same call: the response carries `refunded_joules` (refunds already sent back to your wallet) and `joule_cost` = the price minus it; a refund still in flight completes automatically and is not counted. A failure after the charge is an error and is refunded in full. */
49
+ /* Replies you may get instead of a new proof (none charges): a stored proof of the same type over the same records comes
50
+ * back free (status "already_proven", duplicate true, joule_cost 0); a proof of that record already queued answers status
51
+ * "already_queued". A PLONK proof carries binding_note — what it binds (the first 31 of the 32 bytes of each record hash;
52
+ * quantumResistant binds all 32); show it with the proof. Zero-knowledge records: ProofRefusedError (409, nothing charged). */
49
53
  prove({ resourceType, geographicRegion, supplyChainStage, chunkIds, quantumResistant = false,
50
54
  idempotencyKey, retry = true } = {}) {
51
55
  const body = { quantum_resistant: quantumResistant };
@@ -135,6 +139,9 @@ export class EnyalSubmodule {
135
139
  search({ idempotencyKey, retry = true, ...params } = {}) {
136
140
  return this._t.request(this._base, "GET", "/api/v1/search", { params, idempotencyKey, retry });
137
141
  }
142
+ /** A zero-knowledge record (hash_scheme "commit_v1") cannot be verified by ENYAL — it holds only the commitment — and throws
143
+ * ProofRefusedError (409, nothing charged): decrypt it with crypto.decryptDisclosedRecord and check it with
144
+ * crypto.verifyRecordOnDevice. */
138
145
  verifyAgreement({ agreementChunkId, terms }) {
139
146
  return this._t.request(this._base, "POST", "/api/v1/agreement/verify",
140
147
  { body: { agreement_chunk_id: agreementChunkId, terms } });
@@ -178,7 +185,8 @@ export class EnyalSubmodule {
178
185
  memoryContentQuery(body = {}, { idempotencyKey, retry = true } = {}) {
179
186
  return this._t.request(this._base, "POST", "/api/v1/memory/content-query", { body, idempotencyKey, retry });
180
187
  }
181
- /** NOT retry-safe (archive_routes.py:440). */
188
+ /** Queue a proof of one record. A record already queued answers status "already_queued" (free); a zero-knowledge record
189
+ * throws ProofRefusedError (409, nothing charged). Auto-retry off. */
182
190
  queueProof(chunkId, quantumResistant = false) {
183
191
  return this._t.request(this._base, "POST", "/api/v1/proof/queue",
184
192
  { body: { chunk_id: chunkId, quantum_resistant: quantumResistant } });
package/src/gldai.js CHANGED
@@ -7,8 +7,8 @@
7
7
  * (the TRUE debit = base + the 0.5% rail surcharge). Read the balance with
8
8
  * client.joulepai.balance() and check affordability with client.joulepai.deficit(cost).
9
9
  * The live map/graph read surface is wrapped here too — lookFrom, nearby, relationships
10
- * (the MCP `hops` tool) — alongside companies/deposits/infrastructure/projects/mapdata/
11
- * query; helper names match the MCP tools. Nothing on this surface is MCP-only.
10
+ * (the MCP `hops` tool) — alongside companies/deposits/infrastructure/projects/query;
11
+ * helper names match the MCP tools. Nothing on this surface is MCP-only.
12
12
  * METERED RESPONSES (0.5.5, backend b1b587d / 43ff414 / a3c97f9, 2026-09-22): every metered JSON response
13
13
  * carries ONE top-level `charged_joules` (the all-in debit for THIS call = base + the 0.5% rail fee; the
14
14
  * posed routes lookFrom / mapViewport / lookAt ALSO keep their `price` block as the breakdown, with
@@ -75,18 +75,12 @@ export class GldaiSubmodule {
75
75
  project(projectId) {
76
76
  return this._t.request(this._base, "GET", "/api/v1/projects/{pid}", { pathParams: { pid: projectId } });
77
77
  }
78
- /** CLOSED — do NOT call. GET /api/v1/mapdata (the bulk map-layers surface) is closed to all callers and
79
- * returns an error. Use mapViewport() for map reads. Kept only so the method still resolves for older
80
- * callers. Matches the MCP `mapdata` tool (also marked CLOSED). */
81
- mapdata({ idempotencyKey, ...params } = {}) {
82
- return this._t.request(this._base, "GET", "/api/v1/mapdata", { params, idempotencyKey });
83
- }
84
78
 
85
79
  // ── pricing + live map/graph read surface (2026-09-14; parity with the MCP tools) ──
86
80
  /** The exact per-caller price of a metered call BEFORE you make it — GET /api/v1/billing/quote. FREE
87
81
  * (no charge), needs only a credential (no verification). `path` = the API path the call would hit
88
- * (e.g. "/api/v1/relationships", "/api/v1/look.from", "/api/v1/nearby", "/api/v1/companies/{id}",
89
- * "/api/v1/mapdata"); `hops` = graph depth 1-10 (your tier caps it — Pioneer/FC 3, TEN/Pro 5,
82
+ * (e.g. "/api/v1/relationships", "/api/v1/look.from", "/api/v1/nearby", "/api/v1/companies/{id}");
83
+ * `hops` = graph depth 1-10 (your tier caps it — Pioneer/FC 3, TEN/Pro 5,
90
84
  * Enterprise 10) for a relationships path. Priced at YOUR tier.
91
85
  * Returns { joules (base), rail_fee_joules, joules_all_in, pricing_tier, usd, … } — joules_all_in is
92
86
  * the TRUE debit (base + the 0.5% rail surcharge), so fund THAT, not the base. Same helper as the MCP
@@ -142,8 +136,8 @@ export class GldaiSubmodule {
142
136
  * all four), energy (default false), includeCountryCentroids (default false). AGENT KEYS ONLY; metered
143
137
  * against the CALLING agent's wallet (quote with billingQuote); pins do NOT count against your entity
144
138
  * cap. Response: top-level charged_joules (= price.charged_joules; the price block stays as the breakdown) +
145
- * the metering block (file header). Same as the MCP `map_viewport` tool. Use this — the old /mapdata bulk
146
- * surface is CLOSED. */
139
+ * the metering block (file header). Same as the MCP `map_viewport` tool. Use this (the old /mapdata bulk
140
+ * route was retired 2026-09-30). */
147
141
  mapViewport({ minLat, minLng, maxLat, maxLng, entityType, energy = false,
148
142
  includeCountryCentroids = false, idempotencyKey } = {}) {
149
143
  const params = { energy, include_country_centroids: includeCountryCentroids };