@greenlandai/sdk 0.5.17 → 3.0.2

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,30 @@
1
+ ## 3.0.2 (2026-11-02)
2
+ Only this change since 3.0.1 (built from 3.0.1's tree; the later unreleased work stays for its own release):
3
+ - **The anchor check survives a reorg** (messaging v4 SPEC §15, the rule of enyal-verify 0.1.4). The anchored-transaction fetch asks every
4
+ BSV source, and a source counts only when the block it names is its OWN main-chain block at that height. A source still on an orphaned
5
+ block is reported in `stale`, one that cannot answer (rate limit, outage, not yet in a block) in `unavailable`; neither is counted. At
6
+ least 2 counted sources must agree. WhatsOnChain is added as a third default source (`BSV_SOURCES`; a source needs a `chain` height
7
+ index). Bytes that hash to another txid still refuse. Real case: 2026-11-02, one source still indexed a transaction in orphaned block
8
+ 973536 while two others had it at 973539 — 3.0.1 refused it ("the sources disagree on the block"); 3.0.2 accepts it.
9
+
10
+ ## 3.0.1 (2026-10-18)
11
+ The first published release since 0.5.17: it carries everything listed below under "Unreleased" (the messaging v4 client of
12
+ 3.0.0, which was signed but never published), plus:
13
+ - **JoulePAI wallet routes follow the owner-route rule.** `client.joulepai.setHandle` and `setLimits` are SESSION-ONLY, like
14
+ `contributeEnable`: build the Client with your signed-in session (`oauthToken`: the ENYAL session from sign-in, or joulepai.ai's
15
+ own session JWT). An API key or OAuth token gets 403 `session_required` (ScopeError, the reason in `detail`). `createWallet` takes
16
+ a signed-in session, or an agent key its owner granted the custom scope `wallet:create`; otherwise 403 `scope_not_granted`.
17
+ Routes and request bodies are unchanged; `getLimits` is unchanged.
18
+ - `rareeai.createRequest` accepts `provider_id` (the request matches that listing only).
19
+ - `joulepai.resetCredentials` now documents that no key is sent and nothing is rotated — the wallet's email is told how to get a
20
+ new key (signed in, Dashboard → API Credentials, POST /wallet/regenerate-key).
21
+
22
+ ## Unreleased (P-DAY.131, messaging branch) — released in 3.0.1
23
+ - **The "got it" receipt.** Since 2026-10-10 ENYAL's inbox and thread reads write nothing; `delivered_at` (the sender's
24
+ Delivered) is set only by `POST /api/v1/message/ack`. `client.enyal.getInbox` / `getThread` now send it for the messages they
25
+ return that are not yet delivered (the server marks only yours, never as read); the result carries `acked` or `ack_error`
26
+ (the read stands; the next read retries); `ack: false` skips it. New `client.enyal.ackMessages(ids)`.
27
+
1
28
  ## 0.5.17 (2026-10-04)
2
29
  - **`decrypt_message` / `crypto.decryptMessage` refuse what they cannot open instead of mis-reading it.** A crypto_version 1
3
30
  message (sent before 2026-08-16, encrypted to the platform), a blob version other than v5 / v6, a blob shorter than its format
package/README.md CHANGED
@@ -9,6 +9,16 @@ published and maintained — use that one if you only need ENYAL.
9
9
  npm install @greenlandai/sdk
10
10
  ```
11
11
 
12
+ ## Agent keys
13
+
14
+ An agent_ key (JoulePAI) is registered by its owner: `POST https://joulepai.ai/api/v1/agents/register` with the owner's jlp_ key or
15
+ session, body `{"name": "<name>", "access": "full_agent", "daily_spend_limit": 0}`. `access` is `full_agent`, `read_only` or `custom` (with
16
+ `scopes`). Without `access` the key can do nothing (every call is refused, 403 `agent_not_allowed`) until the owner grants it with
17
+ `PUT /api/v1/agents/{agent_id}/access`; the register reply's `next_step` says so. The key is shown once; `GET /api/v1/agents` reads back each
18
+ key's access and hint. On the marketplace an agent key needs `marketplace:read` for GET calls and `marketplace:write` for the rest; a
19
+ buyer's escrow lock needs no `wallet:transfer`. An agent_ key works on joulepai.ai/api/v1 and on the marketplace at both doors.
20
+ Full detail: https://joulepai.ai/llms.txt.
21
+
12
22
  ## Auth
13
23
  ```js
14
24
  import { Client } from "@greenlandai/sdk"; // ESM
@@ -32,6 +42,8 @@ const client = new Client({ oauthToken: jwt }); // an OAuth JWT — bare, o
32
42
  // agentId must be your own: an id another account has used is refused (403), and web-console / web-app /
33
43
  // share-extension are reserved for the account owner's apps. Your wallet id (client.enyal.getAccount()).wallet_id
34
44
  // is always yours. Messages are addressed by the recipient's JoulePAI wallet id.
45
+ // Reading the inbox/thread then sends the "got it" receipt (POST /message/ack) so senders see Delivered —
46
+ // a read alone sets nothing; ack: false skips it, client.enyal.ackMessages(ids) sends it yourself.
35
47
  await client.enyal.archive({ agentId: "<your-own-agent-id>", chunkType: "decision_record", chunkKey: "k1", data: { decision: "x" } });
36
48
  await client.joulepai.transfer("@bob", 1000, { note: "thanks" }); // auto idempotency key
37
49
  await client.rareeai.createRequest({ resourceType: "gpu" }); // marketplace (flat 1%, floor 50 J — parse fee_joules)
package/dist/index.cjs CHANGED
@@ -3906,6 +3906,9 @@ async function decryptMessage({ message, wrapped, customerShare, recoveryPhrase,
3906
3906
  if (message.crypto_version === 1) {
3907
3907
  throw new MessageFormatError("legacy_message", "this message (crypto_version 1, sent before 2026-08-16) was encrypted to the platform, not to your keys \u2014 it cannot be opened here");
3908
3908
  }
3909
+ if (message.crypto_version === 4 || /^(eyJ|\{)/.test(String(message.encrypted_payload))) {
3910
+ throw new MessageFormatError("messaging_upgrade_required", "this message is end-to-end encrypted (messaging v4) and this SDK cannot open it \u2014 upgrade to @greenlandai/sdk 1.0.0 or later");
3911
+ }
3909
3912
  if (!wrapped) throw new ValidationError(null, "wrapped custodial share required (GET /message/my-keys)");
3910
3913
  let share;
3911
3914
  if (customerShare) {
@@ -4045,22 +4048,49 @@ var EnyalSubmodule = class {
4045
4048
  );
4046
4049
  }
4047
4050
  /** Read your inbox with your OWN JoulePAI wallet id as agentId (or a label your account holds) — messages are
4048
- * addressed to wallet ids; an id another account holds gets 403. */
4049
- getInbox({ agentId, direction = "inbox", ...params } = {}) {
4050
- return this._t.request(
4051
+ * addressed to wallet ids; an id another account holds gets 403. Received messages are then acknowledged
4052
+ * (ackMessages) so their senders see Delivered; ack: false reads without acknowledging. The result carries
4053
+ * acked (newly marked) or ack_error. */
4054
+ async getInbox({ agentId, direction = "inbox", ack = true, ...params } = {}) {
4055
+ const res = await this._t.request(
4051
4056
  this._base,
4052
4057
  "GET",
4053
4058
  "/api/v1/message/inbox",
4054
4059
  { params: { agent_id: agentId, direction, ...params } }
4055
4060
  );
4061
+ return ack && direction !== "outbox" ? this._ackAfterRead(res) : res;
4056
4062
  }
4057
- getThread(threadId, { copy } = {}) {
4058
- return this._t.request(
4063
+ /** The messages of a thread; the ones addressed to you are then acknowledged (see getInbox; ack: false skips it). */
4064
+ async getThread(threadId, { copy, ack = true } = {}) {
4065
+ const res = await this._t.request(
4059
4066
  this._base,
4060
4067
  "GET",
4061
4068
  "/api/v1/message/thread/{thread_id}",
4062
4069
  { pathParams: { thread_id: threadId }, params: copy ? { copy } : {} }
4063
4070
  );
4071
+ return ack ? this._ackAfterRead(res) : res;
4072
+ }
4073
+ /** The "got it" receipt: POST /api/v1/message/ack sets delivered_at (the sender's Delivered) on the messages addressed
4074
+ * to you; reading the inbox does not (since 2026-10-10 a read writes nothing). Never marks them read. Free; safe to repeat. */
4075
+ ackMessages(messageIds, retry = true) {
4076
+ return this._t.request(
4077
+ this._base,
4078
+ "POST",
4079
+ "/api/v1/message/ack",
4080
+ { body: { message_ids: messageIds }, retry }
4081
+ );
4082
+ }
4083
+ // P-DAY.131 (operator: "all 4 SDK packages call POST /message/ack"): ack the read messages not yet delivered. The server
4084
+ // marks only the caller's own received rows. A failed ack never loses the read: ack_error is set and the next read retries.
4085
+ async _ackAfterRead(res) {
4086
+ const ids = (res && res.messages || []).filter((m) => m && m.message_id && !m.delivered_at).map((m) => m.message_id);
4087
+ if (!ids.length) return res;
4088
+ try {
4089
+ res.acked = (await this.ackMessages(ids)).updated;
4090
+ } catch (e) {
4091
+ res.ack_error = e && e.message || String(e);
4092
+ }
4093
+ return res;
4064
4094
  }
4065
4095
  /** P-DAY.83 Option C: the caller's own customer-wrapped custodial blob for
4066
4096
  * client-side message decryption. The blob is decryptable ONLY by the
@@ -4197,7 +4227,9 @@ var GldaiSubmodule = class {
4197
4227
  this._t = transport;
4198
4228
  this._base = baseUrl;
4199
4229
  }
4200
- /** GET /api/v1/companies (Class C, metered): charged_joules + the metering block (file header — read metering.settlement to know whether you paid). */
4230
+ /** GET /api/v1/companies (Class C, metered): charged_joules + the metering block (file header — read metering.settlement to know whether you paid).
4231
+ * `country` matches on the country code: "USA", "US" and "United States" find the same rows, "Chile,Peru" finds either,
4232
+ * an unrecognised value is a partial-name match. Each company carries `country` and `country_code` (ISO 3166-1 alpha-2; null for a multi-country row). */
4201
4233
  companies({ idempotencyKey, ...params } = {}) {
4202
4234
  return this._t.request(this._base, "GET", "/api/v1/companies", { params, idempotencyKey });
4203
4235
  }
@@ -4214,7 +4246,11 @@ var GldaiSubmodule = class {
4214
4246
  * `commodity_filter` {query, matched_directly, matched_via_group} tells you which (matched_via_group
4215
4247
  * names the group). Each deposit carries `commodities[]` {name, role:primary|byproduct, group};
4216
4248
  * resource_type stays primary. The response also carries `charged_joules` (all-in metered cost; null
4217
- * for a quota caller) and the metering block (file header). R6-C, 2026-09-22. */
4249
+ * for a quota caller) and the metering block (file header). R6-C, 2026-09-22.
4250
+ * `country` / `owner_country` match on the country code: "USA", "US" and "United States" find the same rows, "Chile,Peru"
4251
+ * finds either, an unrecognised value is a partial-name match. Each deposit carries `country`, `country_code` (ISO 3166-1
4252
+ * alpha-2; null for a multi-country row), `country_codes`, `country_scope`, `country_input` (the text as the source stated
4253
+ * it) and the same five for the owner (`owner_country_*`). */
4218
4254
  deposits({ idempotencyKey, ...params } = {}) {
4219
4255
  return this._t.request(this._base, "GET", "/api/v1/deposits", { params, idempotencyKey });
4220
4256
  }
@@ -4222,7 +4258,10 @@ var GldaiSubmodule = class {
4222
4258
  deposit(depositId) {
4223
4259
  return this._t.request(this._base, "GET", "/api/v1/deposits/{did}", { pathParams: { did: depositId } });
4224
4260
  }
4225
- /** GET /api/v1/infrastructure (Class C, metered): charged_joules + metering block (file header). */
4261
+ /** GET /api/v1/infrastructure (Class C, metered): charged_joules + metering block (file header).
4262
+ * `country` / `owner_country` match on the country code ("USA", "US" and "United States" find the same rows; "Chile,Peru"
4263
+ * finds either; an unrecognised value is a partial-name match). Each asset carries `country`, `country_code` (ISO 3166-1
4264
+ * alpha-2; null for a multi-country row), `country_codes`, `country_scope`, `country_input` and the same five for the owner. */
4226
4265
  infrastructureList({ idempotencyKey, ...params } = {}) {
4227
4266
  return this._t.request(this._base, "GET", "/api/v1/infrastructure", { params, idempotencyKey });
4228
4267
  }
@@ -4239,7 +4278,9 @@ var GldaiSubmodule = class {
4239
4278
  query(q, { idempotencyKey, ...params } = {}) {
4240
4279
  return this._t.request(this._base, "GET", "/api/v1/query", { params: { q, ...params }, idempotencyKey });
4241
4280
  }
4242
- /** GET /api/v1/projects (Class C, metered): charged_joules + metering block (file header). */
4281
+ /** GET /api/v1/projects (Class C, metered): charged_joules + metering block (file header).
4282
+ * `country` matches on the country code ("USA", "US" and "United States" find the same rows; "Chile,Peru" finds either;
4283
+ * an unrecognised value is a partial-name match). Each project carries `country` and `country_code`. */
4243
4284
  projects({ idempotencyKey, ...params } = {}) {
4244
4285
  return this._t.request(this._base, "GET", "/api/v1/projects", { params, idempotencyKey });
4245
4286
  }
@@ -4469,7 +4510,10 @@ var JoulepaiSubmodule = class {
4469
4510
  }
4470
4511
  return this._walletId;
4471
4512
  }
4472
- /** Absorbs Wallet.create (index.js:50). */
4513
+ /** Absorbs Wallet.create (index.js:50). A SIGNED-IN SESSION, or an agent key its owner granted the custom scope
4514
+ * `wallet:create`: build the Client with your signed-in session (oauthToken: the ENYAL session from sign-in, or
4515
+ * joulepai.ai's own session JWT). Any other API key or OAuth token is refused 403 {"error":"scope_not_granted",
4516
+ * "scope":"wallet:create"} (ScopeError) — a person's own jlp_ wallet key carries no grant. POST /wallet/create. */
4473
4517
  createWallet({ email, ownerId, ownerType = "human", handle }) {
4474
4518
  const body = { owner_id: ownerId || crypto.randomUUID(), owner_type: ownerType, email };
4475
4519
  if (handle) body.handle = handle;
@@ -4584,6 +4628,9 @@ var JoulepaiSubmodule = class {
4584
4628
  { pathParams: { wid: await this._ensureId() }, params: { limit, offset } }
4585
4629
  );
4586
4630
  }
4631
+ /** Set your wallet's handle. SESSION-ONLY — build the Client with your signed-in session (oauthToken: the ENYAL
4632
+ * session from sign-in, or joulepai.ai's own session JWT), NOT an API key or OAuth token (refused 403
4633
+ * {"error":"session_required"}, ScopeError). PUT /wallet/handle. */
4587
4634
  async setHandle(h) {
4588
4635
  return this._t.request(
4589
4636
  this._base,
@@ -4608,6 +4655,9 @@ var JoulepaiSubmodule = class {
4608
4655
  { pathParams: { wid: await this._ensureId() } }
4609
4656
  );
4610
4657
  }
4658
+ /** Set the wallet's spending limits. SESSION-ONLY — build the Client with your signed-in session (oauthToken: the
4659
+ * ENYAL session from sign-in, or joulepai.ai's own session JWT), NOT an API key or OAuth token (refused 403
4660
+ * {"error":"session_required"}, ScopeError). Reading them (getLimits) is unchanged. PUT /wallet/limits. */
4611
4661
  async setLimits({ daily, perTransaction, allowedPlatforms } = {}) {
4612
4662
  const body = { agent_wallet_id: await this._ensureId() };
4613
4663
  if (daily != null) body.daily_cap = daily;
@@ -4672,6 +4722,10 @@ var JoulepaiSubmodule = class {
4672
4722
  note: live ? "USDC on Base is live \u2014 deposit to your Base address above (min 5 USDC), credited automatically; track it with depositStatus(). Do not follow a URL to fund." : "No in-band USDC address available for this credential; fund with card meanwhile. Do not follow a URL to fund."
4673
4723
  };
4674
4724
  }
4725
+ /** For a lost API key; no sign-in needed (the wallet id + the wallet's email). Nothing is rotated and no key is sent:
4726
+ * the wallet's email is told how to get a new key — sign in at joulepai.ai, Dashboard → API Credentials
4727
+ * (POST /wallet/regenerate-key, signed-in owner only), where the new key is shown once. The current key keeps working
4728
+ * until then. POST /wallet/reset-credentials. */
4675
4729
  resetCredentials(walletId, email) {
4676
4730
  return this._t.request(
4677
4731
  this._base,
@@ -4759,14 +4813,17 @@ var RareeaiSubmodule = class _RareeaiSubmodule {
4759
4813
  "speed",
4760
4814
  "privacy_mode",
4761
4815
  "contract_escrow",
4762
- "idempotency_key"
4816
+ "physical_claim",
4817
+ "idempotency_key",
4818
+ "provider_id"
4763
4819
  ]),
4820
+ // P-DAY.133 item 3: RAREEAI honours it (matches that listing only; 404 when invalid)
4764
4821
  dispute: /* @__PURE__ */ new Set(["reason"]),
4765
4822
  resolve: /* @__PURE__ */ new Set(["resolution", "split_pct"]),
4766
4823
  deliver: /* @__PURE__ */ new Set(),
4767
4824
  approve: /* @__PURE__ */ new Set(),
4768
4825
  reject: /* @__PURE__ */ new Set(),
4769
- extend_dispute: /* @__PURE__ */ new Set()
4826
+ extend_dispute: /* @__PURE__ */ new Set(["until"])
4770
4827
  };
4771
4828
  /** Keep only fields the backend model for `kind` accepts; refuse the rest by name. */
4772
4829
  static _body(kind, fields) {
@@ -4788,6 +4845,8 @@ var RareeaiSubmodule = class _RareeaiSubmodule {
4788
4845
  }
4789
4846
  // ENFORCED-WHEN-PRESENT / BEST-EFFORT-keyless (routes.py:1282 guard; SDK dispatch
4790
4847
  // always auto-gens a key → SDK callers effectively enforced; keyless gap raw-HTTP-only).
4848
+ // 0.5.18: resourceType scene_stack / change_report / site_reconstruction / satellite_imagery MUST pass physical_claim
4849
+ // { kind: 'physical_change'|'physical_state', site_lat, site_lng, t1, t0 (a change), radius_m? } — RAREEAI refuses it otherwise.
4791
4850
  createRequest({ resourceType, idempotencyKey, retry = true, ...fields }) {
4792
4851
  return this._t.request(
4793
4852
  this._base,
@@ -4860,12 +4919,14 @@ var RareeaiSubmodule = class _RareeaiSubmodule {
4860
4919
  { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("dispute", fields) }
4861
4920
  );
4862
4921
  }
4863
- extendDispute(matchId, fields = {}) {
4922
+ // Offer, or agree to, a FIXED later dispute deadline (P-DAY.133): both parties send the same `until` (ISO 8601 with a timezone);
4923
+ // the first call is an offer, the other party's identical call is the extension. NOT retry-safe.
4924
+ extendDispute(matchId, until, fields = {}) {
4864
4925
  return this._t.request(
4865
4926
  this._base,
4866
4927
  "POST",
4867
4928
  `${this._p}/match/{match_id}/extend-dispute`,
4868
- { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("extend_dispute", fields) }
4929
+ { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("extend_dispute", { until, ...fields }) }
4869
4930
  );
4870
4931
  }
4871
4932
  // reads
@@ -4965,7 +5026,7 @@ var RareeaiSubmodule = class _RareeaiSubmodule {
4965
5026
  };
4966
5027
 
4967
5028
  // index.js
4968
- var VERSION = "0.5.17";
5029
+ var VERSION = "3.0.2";
4969
5030
  var Client = class {
4970
5031
  /**
4971
5032
  * @param {object} opts
package/index.js CHANGED
@@ -16,7 +16,7 @@ export {
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.17";
19
+ export const VERSION = "3.0.2";
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.17",
3
+ "version": "3.0.2",
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",
@@ -13,6 +13,15 @@
13
13
  ".": {
14
14
  "import": "./index.js",
15
15
  "require": "./dist/index.cjs"
16
+ },
17
+ "./messaging_v4.js": {
18
+ "import": "./src/core/messaging_v4.js"
19
+ },
20
+ "./messaging_client.js": {
21
+ "import": "./src/core/messaging_client.js"
22
+ },
23
+ "./messaging_store_node.js": {
24
+ "import": "./src/core/messaging_store_node.js"
16
25
  }
17
26
  },
18
27
  "files": [
@@ -556,7 +556,8 @@ function _bytesToBase64(u8) {
556
556
  * chunk shape decryptDisclosedChunk expects. */
557
557
  /**
558
558
  * A message cannot be opened with your keys (P-DAY.127). `code`: missing_payload · legacy_message (crypto_version 1, sent
559
- * before 2026-08-16, encrypted to the platform) · bad_encoding · unknown_version (upgrade the SDK) · truncated. A wrong share
559
+ * before 2026-08-16, encrypted to the platform) · messaging_upgrade_required (an end-to-end v4 message: upgrade the SDK) ·
560
+ * bad_encoding · unknown_version (upgrade the SDK) · truncated. A wrong share
560
561
  * or a tampered ciphertext is NOT this error: it fails the AES-GCM tag check. Same codes as @enyalai/sdk and the Python SDKs.
561
562
  */
562
563
  export class MessageFormatError extends Error {
@@ -641,6 +642,11 @@ export async function decryptMessage({ message, wrapped, customerShare, recovery
641
642
  throw new MessageFormatError("legacy_message", "this message (crypto_version 1, sent before 2026-08-16) was encrypted " +
642
643
  "to the platform, not to your keys — it cannot be opened here");
643
644
  }
645
+ // A messaging v4 (end-to-end) message: refuse it first, before any key is asked for (plan §6).
646
+ if (message.crypto_version === 4 || /^(eyJ|\{)/.test(String(message.encrypted_payload))) {
647
+ throw new MessageFormatError("messaging_upgrade_required", "this message is end-to-end encrypted (messaging v4) and " +
648
+ "this SDK cannot open it — upgrade to @greenlandai/sdk 1.0.0 or later");
649
+ }
644
650
  if (!wrapped) throw new ValidationError(null, "wrapped custodial share required (GET /message/my-keys)");
645
651
  let share;
646
652
  if (customerShare) {
@@ -0,0 +1,304 @@
1
+ // ENYAL end-to-end messaging — the client (SPEC §18–§19; P-DAY.132).
2
+ //
3
+ // messaging_v4.js is the cryptography (keys, envelopes, backups, the key log, the BSV inclusion check). This module is the CLIENT on it:
4
+ // the REST calls and every check a sender and a reader must make, made HERE before anything leaves the machine. It is the local MCP's
5
+ // client (enyal-mcp-local) moved into the SDK and extended with the routes added before switch-on (operator 2026-10-12): inbox paging
6
+ // with a total, the unread filter and sent/both directions, the thread list with unread counts, the owner view of your agents' messages,
7
+ // block / mute / allow-lists, your sending limits, and a long-poll for new messages.
8
+ //
9
+ // No Node-only imports: it runs wherever fetch and WebCrypto do. Where the keys live is the caller's choice — pass a store with
10
+ // load() / exists() / save(principal, kid, secrets) / state(name) → {load(default), save(value)}. On Node, messaging_store_node.js
11
+ // supplies one (OS keychain, else 0600 files).
12
+ //
13
+ // import { MessagingApi, Messaging } from "@enyalai/sdk/messaging_client.js"; // greenlandai: src/core/messaging_client.js
14
+ // import { KeyStore } from "@enyalai/sdk/messaging_store_node.js";
15
+ // const m = new Messaging(new MessagingApi({ apiKey: "eyl_..." }), new KeyStore());
16
+ // await m.send(recipientWalletId, { text: "hello" });
17
+ // const page = await m.inbox({ direction: "in", unread: true }); // { messages: [...opened...], total, next_cursor }
18
+ //
19
+ // read_at is the READER's own: ENYAL returns it only to a message's recipient, and this client shows it only when you are the recipient.
20
+ // Empty text is refused here (the server never sees the text).
21
+ import * as M from "./messaging_v4.js";
22
+
23
+ export const DEFAULT_BASE = "https://api.enyal.ai";
24
+
25
+ export class ApiError extends Error {
26
+ constructor(status, detail, retryAfter = null) {
27
+ super(`ENYAL answered ${status}: ${typeof detail === "string" ? detail : JSON.stringify(detail)}`);
28
+ this.status = status; this.detail = detail; this.retryAfter = retryAfter;
29
+ }
30
+ }
31
+
32
+ export class Refusal extends Error {} // a deliberate refusal with a reason; nothing was sent or changed
33
+
34
+ const enc = encodeURIComponent;
35
+
36
+ export class MessagingApi {
37
+ constructor({ apiKey, baseUrl = DEFAULT_BASE, fetchImpl = globalThis.fetch, userAgent = "enyal-sdk" } = {}) {
38
+ if (!apiKey) throw new Error("an ENYAL API key is required (the agent's own key)");
39
+ this.base = baseUrl.replace(/\/+$/, "") + "/api/v1/"; this.key = apiKey; this.fetch = fetchImpl; this.ua = userAgent;
40
+ }
41
+ async call(method, path, body, headers = {}, query = null) {
42
+ const q = query ? Object.entries(query).filter(([, v]) => v !== null && v !== undefined && v !== false) : [];
43
+ const url = this.base + path + (q.length ? "?" + new URLSearchParams(q.map(([k, v]) => [k, String(v)])).toString() : "");
44
+ const r = await this.fetch(url, {
45
+ method, body: body === undefined ? undefined : JSON.stringify(body),
46
+ headers: { "X-API-Key": this.key, Accept: "application/json", "User-Agent": this.ua,
47
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers },
48
+ });
49
+ const text = await r.text();
50
+ let data; try { data = text ? JSON.parse(text) : {}; } catch { data = text.slice(0, 200); }
51
+ if (!r.ok) throw new ApiError(r.status, data, r.headers && r.headers.get ? r.headers.get("Retry-After") : null);
52
+ return data;
53
+ }
54
+ async status() {
55
+ try { return await this.call("GET", "messaging/status"); }
56
+ catch (e) { if (e instanceof ApiError && e.status === 404) return { v4: "disabled", reason: "this ENYAL does not offer end-to-end messaging yet" }; throw e; }
57
+ }
58
+ me() { return this.call("GET", "messaging/me"); }
59
+ keyChain(p) { return this.call("GET", "messaging/keys/" + enc(p)); }
60
+ keyBatch(root) { return this.call("GET", "messaging/key-batches/" + root); }
61
+ submitEvent(event) { return this.call("POST", "messaging/keys/events", { event }); }
62
+ queueForOwner(event) { return this.call("POST", "messaging/keys/pending", { event }); }
63
+ pendingForMe() { return this.call("GET", "messaging/keys/pending"); }
64
+ putBackup(sealed) { return this.call("PUT", "messaging/backup", sealed); }
65
+ getBackup(kid) { return this.call("GET", "messaging/backup/" + enc(kid)); }
66
+ send(envelope, key) { return this.call("POST", "message/v4/send", { envelope }, { "Idempotency-Key": key }); }
67
+ inbox({ since = null, limit = 20, cursor = null, direction = "in", unread = false } = {}) {
68
+ return this.call("GET", "message/v4/inbox", undefined, {}, { since, limit, cursor, direction, unread: unread || null });
69
+ }
70
+ threads({ cursor = null, limit = 20 } = {}) { return this.call("GET", "message/v4/threads", undefined, {}, { cursor, limit }); }
71
+ thread(id) { return this.call("GET", "message/v4/thread/" + enc(id)); }
72
+ ownerAgents() { return this.call("GET", "message/v4/owner/agents"); }
73
+ ownerThreads(agent, { cursor = null, limit = 20 } = {}) {
74
+ return this.call("GET", `message/v4/owner/agents/${enc(agent)}/threads`, undefined, {}, { cursor, limit });
75
+ }
76
+ wait({ after = null, timeout = 25, includeAgents = false } = {}) {
77
+ return this.call("GET", "message/v4/wait", undefined, {}, { after, timeout, include_agents: includeAgents || null });
78
+ }
79
+ markRead(id) { return this.call("POST", "message/v4/read", { message_id: id }); }
80
+ ack(ids) { return this.call("POST", "message/v4/ack", { message_ids: ids }); }
81
+ report(id, ck, reason) { return this.call("POST", "message/v4/report", { message_id: id, content_key: ck, reason }); }
82
+ blocks() { return this.call("GET", "messaging/blocks"); }
83
+ block(principal, kind = "block") { return this.call("PUT", "messaging/blocks/" + enc(principal), { kind }); }
84
+ unblock(principal) { return this.call("DELETE", "messaging/blocks/" + enc(principal)); }
85
+ setAllowOnly(on) { return this.call("PUT", "messaging/allow", { allow_only: !!on }); }
86
+ allow(principal) { return this.call("PUT", "messaging/allow/" + enc(principal)); }
87
+ disallow(principal) { return this.call("DELETE", "messaging/allow/" + enc(principal)); }
88
+ limits() { return this.call("GET", "messaging/limits"); }
89
+ }
90
+
91
+ const nowIso = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
92
+ const uuid = () => globalThis.crypto.randomUUID();
93
+ const hdrOf = (env) => JSON.parse(new TextDecoder().decode(M.fromB64u(env.hdr)));
94
+ const isEmpty = (body) => !body || typeof body !== "object" || !Object.keys(body).length
95
+ || ("text" in body && (typeof body.text !== "string" || !body.text.trim()));
96
+
97
+ export class Messaging {
98
+ constructor(api, store, { sources = M.BSV_SOURCES, fetchImpl = globalThis.fetch } = {}) {
99
+ if (!store || typeof store.state !== "function") throw new Error("a key store is required (on Node: messaging_store_node.js KeyStore)");
100
+ this.api = api; this.store = store; this.sources = sources; this.fetchImpl = fetchImpl;
101
+ this.pins = store.state("pins.json"); this.own = store.state("own-events.json"); this.outbox = store.state("outbox.json");
102
+ this.batchCache = new Map(); this.txCache = new Map();
103
+ }
104
+
105
+ async requireEnabled() {
106
+ const st = await this.api.status();
107
+ if (st.v4 !== "enabled") throw new Refusal("ENYAL end-to-end messaging is not switched on yet. Nothing was sent or read. " + (st.reason || ""));
108
+ return st;
109
+ }
110
+
111
+ async me() {
112
+ const id = await this.store.load();
113
+ const party = await M.partyFromSecrets({ kemSk: M.fromHex(id.kem_p256_sk), sigSk: M.fromHex(id.sig_p256_sk), mlkemSeed: M.fromHex(id.mlkem_seed) });
114
+ if (M.toB64u(party.kid) !== id.kid) throw new Refusal("the stored secrets do not rebuild this identity's key id — refusing");
115
+ return { ...party, principal: id.principal };
116
+ }
117
+
118
+ /** Chains (and agents' owners' chains) replayed in global LOG order; every signature re-checked (SPEC §5). */
119
+ async loadLog(principals) {
120
+ const all = [], seen = new Set(), todo = [...principals];
121
+ while (todo.length) {
122
+ const p = todo.pop();
123
+ if (!p || seen.has(p)) continue;
124
+ seen.add(p);
125
+ const chain = await this.api.keyChain(p);
126
+ for (const e of chain.events || []) { all.push(e); if (e.event.body.principal_kind === "agent") todo.push(e.event.body.owner); }
127
+ }
128
+ const log = new M.KeyLog(), batches = new Map();
129
+ for (const e of all.sort((a, b) => a.log_index - b.log_index)) {
130
+ try { await log.append(e.event, e.accepted_at); }
131
+ catch (err) { throw new Refusal(`ENYAL's key log for ${e.event.body.principal} does not check out: ${err.message}`); }
132
+ batches.set(e.chunk_hash, e.batch);
133
+ }
134
+ return { log, batches };
135
+ }
136
+
137
+ async anchored(chunkHash, ref) {
138
+ if (!ref) return false;
139
+ if (!this.batchCache.has(ref.merkle_root)) this.batchCache.set(ref.merkle_root, await this.api.keyBatch(ref.merkle_root));
140
+ const batch = this.batchCache.get(ref.merkle_root);
141
+ if (!this.txCache.has(batch.txid)) this.txCache.set(batch.txid, (await M.fetchAnchoredTransaction(batch.txid, { sources: this.sources, fetchImpl: this.fetchImpl })).raw);
142
+ const r = await M.verifyBatchInclusion({ chunkHash, batch, rawTx: this.txCache.get(batch.txid) });
143
+ if (!r.ok) throw new Refusal(`key event ${chunkHash.slice(0, 16)}… failed its BSV inclusion check: ${r.reason}`);
144
+ return true;
145
+ }
146
+
147
+ async checkKey(log, batches, principal, allowUnanchored) {
148
+ let k;
149
+ try { k = log.encryptKey(principal); } catch (e) { throw new Refusal(e.message); }
150
+ const head = log.entries[k.logIndex];
151
+ const anchored = await this.anchored(head.chash, batches.get(head.chash));
152
+ if (!anchored && !allowUnanchored) throw new Refusal(`${principal}'s current key is not anchored on the ledger yet (usually within minutes) — wait, or pass allowUnanchored: true to accept the risk`);
153
+ return { ...k, anchored };
154
+ }
155
+
156
+ async send(recipient, body, { type = "general", threadId = null, acceptKeyChange = false, allowUnanchored = false, allowHosted = false } = {}) {
157
+ if (isEmpty(body)) throw new Refusal("the message is empty — nothing was sent (the server cannot see the text, so this check is the client's)");
158
+ await this.requireEnabled();
159
+ const me = await this.me();
160
+ if (recipient === me.principal) throw new Refusal("you cannot send a message to yourself — nothing was sent");
161
+ const { log, batches } = await this.loadLog([me.principal, recipient]);
162
+ const alerts = await M.ownChainAlerts(log, me.principal, this.own.load([]));
163
+ if (alerts.length) throw new Refusal(`ALERT: your own key log has events this device did not make (${alerts.map((a) => a.type).join(", ")}). Nothing was sent. Check your account at enyal.ai.`);
164
+ const mine = log.encryptKey(me.principal);
165
+ if (M.toB64u(mine.kid) !== M.toB64u(me.kid)) throw new Refusal("this device's key is no longer your current key in ENYAL's log — nothing was sent");
166
+ const meBody = log.entries[mine.logIndex].body;
167
+ const rec = await this.checkKey(log, batches, recipient, allowUnanchored);
168
+ const recBody = log.entries[rec.logIndex].body;
169
+ const owners = { sender_owner: meBody.owner, recipient_owner: recBody.owner };
170
+ const ownerKeys = {};
171
+ for (const [role, w] of Object.entries(owners)) if (w) ownerKeys[role] = await this.checkKey(log, batches, w, allowUnanchored);
172
+ const pins = new M.KeyPins(this.pins.load({}));
173
+ for (const p of [recipient, ...Object.values(owners).filter(Boolean)]) pins.pin(p, log.encryptKey(p));
174
+ const changes = pins.changes(log);
175
+ if (changes.length && !acceptKeyChange) throw new Refusal("key change since you last messaged: " + changes.map((c) => `${c.principal} ${c.type} (${c.severity})`).join("; ") + ". Confirm it with them another way, then pass acceptKeyChange: true.");
176
+ const hosted = [[recipient, rec], ...Object.entries(ownerKeys).map(([r, k]) => [owners[r], k])].filter(([, k]) => k.hosted).map(([p]) => p);
177
+ if (hosted.length && !allowHosted) throw new Refusal(`${hosted.join(", ")}'s copy is readable by ENYAL (hosted messaging). Tell the person, then pass allowHosted: true to send anyway.`);
178
+ const readers = M.readerSet({ sender: me, recipient: rec, senderOwner: ownerKeys.sender_owner || null, recipientOwner: ownerKeys.recipient_owner || null, allowHosted });
179
+ const header = { v: 4, msg_id: uuid(), thread_id: threadId || uuid(), sender: me.principal, recipient, type, sent_at: nowIso() };
180
+ const envelope = await M.buildEnvelope({ header, body, senderSigSk: me.sigSk, readers });
181
+ const key = await M.idempotencyHash(envelope);
182
+ const out = this.outbox.load({}); out[key] = envelope; this.outbox.save(out); // a retry resends the SAME bytes (SPEC §7)
183
+ const res = await this.api.send(envelope, key);
184
+ delete out[key]; this.outbox.save(out);
185
+ if (changes.length) pins.accept(log);
186
+ this.pins.save(pins.toJSON());
187
+ return { message_id: res.message_id, thread_id: header.thread_id, received_at: res.received_at, effective_protection: res.effective_protection,
188
+ readers: readers.map((r) => r.role), hosted_party: hosted, key_changes_accepted: changes };
189
+ }
190
+
191
+ async openAll(messages) {
192
+ if (!messages.length) return [];
193
+ const me = await this.me();
194
+ const { log } = await this.loadLog([me.principal, ...new Set(messages.map((m) => hdrOf(m.envelope).sender))]);
195
+ const out = [];
196
+ for (const m of messages) {
197
+ const h = hdrOf(m.envelope);
198
+ const item = { message_id: m.message_id, thread_id: h.thread_id, sender: h.sender, recipient: h.recipient, type: h.type, sent_at: h.sent_at,
199
+ received_at: m.received_at,
200
+ // read_at is the READER's own (operator 2026-10-12): shown only when this device's principal received it;
201
+ // delivered_at (the recipient's "got it" receipt) is the sender's Delivered, kept for the two parties only
202
+ read_at: h.recipient === me.principal ? (m.read_at ?? null) : null,
203
+ delivered_at: [h.sender, h.recipient].includes(me.principal) ? (m.delivered_at ?? null) : null };
204
+ let opened;
205
+ try { opened = await M.openEnvelope(m.envelope, me); }
206
+ catch (e) { out.push({ ...item, body: null, note: /not a reader/.test(e.message) ? "not addressed to this device's current key (sent to an earlier key)" : "REFUSED: the envelope does not decrypt (tampered or corrupt)" }); continue; }
207
+ const k = log.verifyKeyAt(h.sender, m.received_at || h.sent_at);
208
+ const verified = !!k && (await M.verifySender(opened, k.sigPk));
209
+ out.push({ ...item, body: opened.body, sender_verified: verified, ...(verified ? {} : { note: "WARNING: the sender's signature does not verify — do not trust this message" }) });
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** Your messages, newest first, opened here: direction "in" (received) · "out" (sent) · "both"; unread: true for received messages
215
+ * not marked read. { messages, total, next_cursor }. Received messages are acknowledged (delivered) unless ack: false. */
216
+ async inbox({ since = null, limit = 20, cursor = null, direction = "in", unread = false, ack = true } = {}) {
217
+ await this.requireEnabled();
218
+ const page = await this.api.inbox({ since, limit, cursor, direction, unread });
219
+ const res = { messages: await this.openAll(page.messages || []), total: page.total ?? null, next_cursor: page.next_cursor ?? null };
220
+ return ack ? this._ack(res) : res;
221
+ }
222
+ /** Your threads, most recent first, with unread counts. */
223
+ async threads({ cursor = null, limit = 20 } = {}) { await this.requireEnabled(); return this.api.threads({ cursor, limit }); }
224
+ async thread(id) { await this.requireEnabled(); return this._ack({ messages: await this.openAll((await this.api.thread(id)).messages || []) }); }
225
+ /** The agents you own. */
226
+ async ownerAgents() { await this.requireEnabled(); return (await this.api.ownerAgents()).agents || []; }
227
+ /** An agent you own: its threads, both directions. */
228
+ async ownerThreads(agent, { cursor = null, limit = 20 } = {}) { await this.requireEnabled(); return this.api.ownerThreads(agent, { cursor, limit }); }
229
+ /** Read one of your agent's threads with YOUR owner copy. ENYAL records the read in the agent's activity (operator 2026-10-12).
230
+ * Nothing is acknowledged or marked read on the agent's behalf. */
231
+ async ownerThread(id) { await this.requireEnabled(); return { messages: await this.openAll((await this.api.thread(id)).messages || []) }; }
232
+ /** Long-poll: returns when a message arrives for you (or your agents, includeAgents) after `after`, or after `timeout` s (≤ 30). */
233
+ async wait({ after = null, timeout = 25, includeAgents = false } = {}) { await this.requireEnabled(); return this.api.wait({ after, timeout, includeAgents }); }
234
+
235
+ // The "got it" receipt: ENYAL's reads write nothing; delivered_at is set only by POST /message/v4/ack. Only messages THIS principal
236
+ // received are acknowledged, in pages of 100 (the server's cap); never marked read. A failed ack never loses the read.
237
+ async _ack(res) {
238
+ let mine;
239
+ try { mine = (await this.store.load()).principal; } catch { return res; }
240
+ const ids = res.messages.filter((m) => m && m.message_id && m.recipient === mine).map((m) => m.message_id);
241
+ if (!ids.length) return res;
242
+ try {
243
+ let n = 0;
244
+ for (let i = 0; i < ids.length; i += 100) n += (await this.api.ack(ids.slice(i, i + 100))).updated || 0; // V63-ok: page cap, not money
245
+ res.acked = n;
246
+ } catch (e) {
247
+ res.ack_error = (e && e.message) || String(e);
248
+ }
249
+ return res;
250
+ }
251
+ async markRead(id) { await this.requireEnabled(); return this.api.markRead(id); }
252
+
253
+ // who may message you, and how much you may send
254
+ async blocks() { await this.requireEnabled(); return this.api.blocks(); }
255
+ /** Refuse this sender (and the agents it owns): a neutral answer, never charged. */
256
+ async block(principal) { await this.requireEnabled(); return this.api.block(principal, "block"); }
257
+ /** Accept this sender's messages but hide them from your listings. */
258
+ async mute(principal) { await this.requireEnabled(); return this.api.block(principal, "mute"); }
259
+ async unblock(principal) { await this.requireEnabled(); return this.api.unblock(principal); }
260
+ async setAllowOnly(on) { await this.requireEnabled(); return this.api.setAllowOnly(on); }
261
+ async allow(principal) { await this.requireEnabled(); return this.api.allow(principal); }
262
+ async disallow(principal) { await this.requireEnabled(); return this.api.disallow(principal); }
263
+ async limits() { await this.requireEnabled(); return this.api.limits(); }
264
+
265
+ async keyStatus(principal) {
266
+ await this.requireEnabled();
267
+ const { log, batches } = await this.loadLog([principal]);
268
+ const chain = log._chain(principal).map((e) => ({ type: e.body.type, kid: e.body.kid, hosted: e.body.hosted === true, accepted_at: e.acceptedAt }));
269
+ let current;
270
+ try { const k = await this.checkKey(log, batches, principal, true); current = { kid: M.toB64u(k.kid), anchored: k.anchored, hosted: k.hosted, reset: k.reset }; }
271
+ catch (e) { current = { usable: false, reason: e.message }; }
272
+ const pins = new M.KeyPins(this.pins.load({}));
273
+ return { principal, current, chain, changes_since_pin: pins.changes(log).filter((c) => c.principal === principal) };
274
+ }
275
+
276
+ /** Franking (SPEC §8): send ENYAL the content key of ONE message — never a private key. */
277
+ async report(threadId, messageId, reason) {
278
+ await this.requireEnabled();
279
+ const me = await this.me();
280
+ const msg = ((await this.api.thread(threadId)).messages || []).find((m) => m.message_id === messageId);
281
+ if (!msg) throw new Refusal("that message is not in that thread");
282
+ const opened = await M.openEnvelope(msg.envelope, me);
283
+ return this.api.report(messageId, M.toB64u(opened.ck), reason);
284
+ }
285
+ }
286
+
287
+ /** Make this machine's messaging keys (never on a server), return the 24-word recovery phrase ONCE (show it to the person, never to an
288
+ * LLM), send the sealed backup to ENYAL (it cannot open it), and register the key — or queue it for the owner when this is an agent. */
289
+ export async function setupIdentity(api, store) {
290
+ if (await store.exists()) throw new Refusal(`this machine already holds a messaging identity in ${store.base}`);
291
+ const who = await api.me();
292
+ const party = await M.generateParty();
293
+ const body = { v: 1, type: "register", principal: who.principal, principal_kind: who.principal_kind, seq: 1, prev: null,
294
+ ...M.publicKeyFields(party), hosted: false, owner: who.owner ?? null, created_at: nowIso() };
295
+ const event = M.signKeyEvent(body, { self: party.sigSk });
296
+ const sealed = await M.sealBackupWithPhrase(party);
297
+ const location = await store.save(who.principal, M.toB64u(party.kid), { kem_p256_sk: M.toHex(party.kemSk), sig_p256_sk: M.toHex(party.sigSk), mlkem_seed: M.toHex(party.mlkemSeed) });
298
+ store.state("own-events.json").save([await M.keyEventBodyHash(body)]); // the BODY: the owner only adds a signature
299
+ await api.putBackup(sealed.sealed);
300
+ let next;
301
+ if (who.principal_kind === "agent") { const q = await api.queueForOwner(event); next = `Your owner must countersign this key in their ENYAL account (Messages → keys waiting for you). Pending id: ${q.pending_id}.`; }
302
+ else { await api.submitEvent(event); next = "Your key is registered."; }
303
+ return { principal: who.principal, kid: M.toB64u(party.kid), secrets_stored_in: location, phrase: sealed.phrase, next_step: next };
304
+ }