@greenlandai/sdk 0.5.3 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -117,6 +117,7 @@ var IDEMPOTENCY_MAP = {
117
117
  "GET /api/v1/nearby": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
118
118
  "GET /api/v1/relationships": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
119
119
  "GET /api/v1/map.viewport": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
120
+ "GET /api/v1/look.at": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
120
121
  // (cf) ENYAL metered GET — joins Class C header class (server reads X-Idempotency-Key per the Option-B switch)
121
122
  "GET /api/v1/search": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
122
123
  // Class D — transfer-class
@@ -218,7 +219,9 @@ var Transport = class {
218
219
  params = null,
219
220
  idempotencyKey = null,
220
221
  retry = true,
221
- maxRetries = DEFAULT_MAX_RETRIES
222
+ maxRetries = DEFAULT_MAX_RETRIES,
223
+ accept = null,
224
+ raw = false
222
225
  } = {}) {
223
226
  let headers = this._isApiKey ? { "X-API-Key": this._credential } : { Authorization: `Bearer ${this._credential}` };
224
227
  const d = dispatch(method, pathTemplate, body, headers, idempotencyKey);
@@ -238,7 +241,7 @@ var Transport = class {
238
241
  const t0 = Date.now();
239
242
  for (; ; ) {
240
243
  try {
241
- const result = await this._once(method, url, headers, body);
244
+ const result = await this._once(method, url, headers, body, { accept, raw });
242
245
  this._count("sdk.requests");
243
246
  this._hist("sdk.request.duration", (Date.now() - t0) / 1e3);
244
247
  if (result && result.duplicate === true) {
@@ -263,7 +266,7 @@ var Transport = class {
263
266
  }
264
267
  }
265
268
  }
266
- async _once(method, url, headers, body) {
269
+ async _once(method, url, headers, body, { accept = null, raw = false } = {}) {
267
270
  const redacted = { ...headers };
268
271
  if ("Authorization" in redacted) redacted.Authorization = "[REDACTED]";
269
272
  if ("X-API-Key" in redacted) redacted["X-API-Key"] = "[REDACTED]";
@@ -271,6 +274,7 @@ var Transport = class {
271
274
  let resp;
272
275
  try {
273
276
  const opts2 = { method, headers: { ...headers } };
277
+ if (accept) opts2.headers["Accept"] = accept;
274
278
  if (body != null) {
275
279
  opts2.headers["Content-Type"] = "application/json";
276
280
  opts2.body = JSON.stringify(body);
@@ -293,6 +297,16 @@ var Transport = class {
293
297
  if (typeof detail === "object") detail = JSON.stringify(detail);
294
298
  throw errorForStatus(resp.status, String(detail), requestId, retryAfter);
295
299
  }
300
+ if (raw) {
301
+ const ct = resp.headers?.get ? resp.headers.get("content-type") || "" : "";
302
+ if (ct.startsWith("application/json")) return resp.json();
303
+ const buf = await resp.arrayBuffer();
304
+ const provenance = {};
305
+ if (resp.headers?.forEach) resp.headers.forEach((v, k) => {
306
+ if (k.toLowerCase().startsWith("x-")) provenance[k] = v;
307
+ });
308
+ return { _raw: true, content_type: ct, content: new Uint8Array(buf), provenance };
309
+ }
296
310
  if (resp.status === 204) return null;
297
311
  return resp.json();
298
312
  }
@@ -3981,39 +3995,59 @@ var GldaiSubmodule = class {
3981
3995
  this._t = transport;
3982
3996
  this._base = baseUrl;
3983
3997
  }
3998
+ /** GET /api/v1/companies (Class C, metered): charged_joules + the metering block (file header — read metering.settlement to know whether you paid). */
3984
3999
  companies({ idempotencyKey, ...params } = {}) {
3985
4000
  return this._t.request(this._base, "GET", "/api/v1/companies", { params, idempotencyKey });
3986
4001
  }
4002
+ /** GET /api/v1/companies/{id} — metered: charged_joules + metering block (file header). */
3987
4003
  company(companyId) {
3988
4004
  return this._t.request(this._base, "GET", "/api/v1/companies/{cid}", { pathParams: { cid: companyId } });
3989
4005
  }
4006
+ /** GET /api/v1/deposits — list resource deposits (Class C, metered). Filters via the params object
4007
+ * (API names, passed through): resource_type, country, status, owner_country, max_port_km, search,
4008
+ * limit (<=100), offset, and `commodity`. ⚠ `commodity` filters by the commodity GRAPH, not the
4009
+ * resource_type string: it matches a deposit that CONTAINS the commodity directly, OR CONTAINS a group
4010
+ * the commodity is MEMBER_OF — so commodity:"neodymium" returns EVERY rare-earth-element deposit,
4011
+ * including ones whose name never says "neodymium" (it would look broken otherwise). The top-level
4012
+ * `commodity_filter` {query, matched_directly, matched_via_group} tells you which (matched_via_group
4013
+ * names the group). Each deposit carries `commodities[]` {name, role:primary|byproduct, group};
4014
+ * resource_type stays primary. The response also carries `charged_joules` (all-in metered cost; null
4015
+ * for a quota caller) and the metering block (file header). R6-C, 2026-09-22. */
3990
4016
  deposits({ idempotencyKey, ...params } = {}) {
3991
4017
  return this._t.request(this._base, "GET", "/api/v1/deposits", { params, idempotencyKey });
3992
4018
  }
4019
+ /** GET /api/v1/deposits/{id} — metered: charged_joules + metering block (file header). */
3993
4020
  deposit(depositId) {
3994
4021
  return this._t.request(this._base, "GET", "/api/v1/deposits/{did}", { pathParams: { did: depositId } });
3995
4022
  }
4023
+ /** GET /api/v1/infrastructure (Class C, metered): charged_joules + metering block (file header). */
3996
4024
  infrastructureList({ idempotencyKey, ...params } = {}) {
3997
4025
  return this._t.request(this._base, "GET", "/api/v1/infrastructure", { params, idempotencyKey });
3998
4026
  }
4027
+ /** GET /api/v1/infrastructure/{id} — metered: charged_joules + metering block (file header). */
3999
4028
  infrastructure(infraId) {
4000
4029
  return this._t.request(this._base, "GET", "/api/v1/infrastructure/{iid}", { pathParams: { iid: infraId } });
4001
4030
  }
4002
- /** GET /api/v1/query — the natural-language intelligence query, metered per call (Class C). WORKS FOR
4003
- * JOULE-METERED AGENTS: they pay per query and are EXEMPT from the human NL access gates (the old
4004
- * charged-then-403 for agents was fixed; api.py:1414 `_is_joule_agent` bypasses the email-verify /
4005
- * door / entitlement checks, which apply to human accounts only). Humans need a verified ENYAL
4006
- * identity + NL access ($10/level). Metered against the CALLING agent's wallet — quote with
4007
- * billingQuote("/api/v1/query") first. */
4031
+ /** GET /api/v1/query — the natural-language intelligence query. CLOSED TO ALL CALLERS TODAY (2026-09-22,
4032
+ * operator ruling): to agents by the August 2026 ruling (not part of the agent launch — the meter refuses
4033
+ * an agent 403 BEFORE any charge), to human sessions on capacity grounds (HUMAN_QUERY_ENABLED). It reopens
4034
+ * when there are servers for it. Nothing is charged for a refused call. Use the structured surface instead:
4035
+ * companies / deposits / infrastructure / projects / relationships / lookFrom / nearby / mapViewport. Kept
4036
+ * so the method resolves; matches the served llms.txt and spec. */
4008
4037
  query(q, { idempotencyKey, ...params } = {}) {
4009
4038
  return this._t.request(this._base, "GET", "/api/v1/query", { params: { q, ...params }, idempotencyKey });
4010
4039
  }
4040
+ /** GET /api/v1/projects (Class C, metered): charged_joules + metering block (file header). */
4011
4041
  projects({ idempotencyKey, ...params } = {}) {
4012
4042
  return this._t.request(this._base, "GET", "/api/v1/projects", { params, idempotencyKey });
4013
4043
  }
4044
+ /** GET /api/v1/projects/{id} — metered: charged_joules + metering block (file header). */
4014
4045
  project(projectId) {
4015
4046
  return this._t.request(this._base, "GET", "/api/v1/projects/{pid}", { pathParams: { pid: projectId } });
4016
4047
  }
4048
+ /** CLOSED — do NOT call. GET /api/v1/mapdata (the bulk map-layers surface) is closed to all callers and
4049
+ * returns an error. Use mapViewport() for map reads. Kept only so the method still resolves for older
4050
+ * callers. Matches the MCP `mapdata` tool (also marked CLOSED). */
4017
4051
  mapdata({ idempotencyKey, ...params } = {}) {
4018
4052
  return this._t.request(this._base, "GET", "/api/v1/mapdata", { params, idempotencyKey });
4019
4053
  }
@@ -4021,7 +4055,8 @@ var GldaiSubmodule = class {
4021
4055
  /** The exact per-caller price of a metered call BEFORE you make it — GET /api/v1/billing/quote. FREE
4022
4056
  * (no charge), needs only a credential (no verification). `path` = the API path the call would hit
4023
4057
  * (e.g. "/api/v1/relationships", "/api/v1/look.from", "/api/v1/nearby", "/api/v1/companies/{id}",
4024
- * "/api/v1/mapdata"); `hops` = graph depth 1-20 for a relationships path. Priced at YOUR tier.
4058
+ * "/api/v1/mapdata"); `hops` = graph depth 1-10 (your tier caps it — Pioneer/FC 3, TEN/Pro 5,
4059
+ * Enterprise 10) for a relationships path. Priced at YOUR tier.
4025
4060
  * Returns { joules (base), rail_fee_joules, joules_all_in, pricing_tier, usd, … } — joules_all_in is
4026
4061
  * the TRUE debit (base + the 0.5% rail surcharge), so fund THAT, not the base. Same helper as the MCP
4027
4062
  * `billing_quote` tool. Metered reads debit the CALLING agent's OWN wallet (not the owner's); read the
@@ -4034,7 +4069,9 @@ var GldaiSubmodule = class {
4034
4069
  * (entityType+id). Metered against the CALLING agent's wallet (base + 0.5% rail; quote with
4035
4070
  * billingQuote). entityType behaves two ways (backend 2026-09-14): entityType ALONE (with lat/lng)
4036
4071
  * FILTERS the frame to that type; entityType + id ANCHORS the pose at that entity and keeps ALL types;
4037
- * an unknown entityType is a 400 before any charge. Same as the MCP `look_from` tool. */
4072
+ * an unknown entityType is a 400 before any charge. Response: top-level charged_joules (the all-in debit —
4073
+ * the same figure as price.charged_joules; the price block stays as the breakdown) + the metering block
4074
+ * (file header). Same as the MCP `look_from` tool. */
4038
4075
  lookFrom({
4039
4076
  lat,
4040
4077
  lng,
@@ -4053,7 +4090,8 @@ var GldaiSubmodule = class {
4053
4090
  return this._t.request(this._base, "GET", "/api/v1/look.from", { params, idempotencyKey });
4054
4091
  }
4055
4092
  /** GET /api/v1/nearby — entities near a location; here entityType IS a content filter. Metered against
4056
- * the CALLING agent's wallet (quote with billingQuote). Same as the MCP `nearby` tool. */
4093
+ * the CALLING agent's wallet (quote with billingQuote): charged_joules + metering block (file header).
4094
+ * Same as the MCP `nearby` tool. */
4057
4095
  nearby({
4058
4096
  lat,
4059
4097
  lng,
@@ -4069,8 +4107,12 @@ var GldaiSubmodule = class {
4069
4107
  }
4070
4108
  /** GET /api/v1/relationships — labelled relationship hops (the MCP `hops` tool). `entity` is the START
4071
4109
  * NODE, matched as a case-insensitive SUBSTRING of an entity NAME (never an id: "3" matches any name
4072
- * containing "3"), so pass a full, distinctive name. `hops` = depth 1-10. Metered per hop against the
4073
- * CALLING agent's wallet (quote with billingQuote("/api/v1/relationships", n)). */
4110
+ * containing "3"), so pass a full, distinctive name. `hops` = depth 1-10. relationType (one relation label,
4111
+ * e.g. OPERATES, CONTAINS, MEMBER_OF) is checked against the API's allow-list on BOTH paths (with or without
4112
+ * entity, backend a3c97f9): an unknown label is a 400 naming the allowed set, BEFORE any charge — never an
4113
+ * empty 200. Metered per hop against the CALLING agent's wallet (quote with
4114
+ * billingQuote("/api/v1/relationships", n)): the response carries charged_joules (the settled all-in — 0 for
4115
+ * an empty result) + the metering block (file header). */
4074
4116
  relationships({ entity, hops = 1, relationType, search, limit = 50, offset = 0, idempotencyKey } = {}) {
4075
4117
  const params = { hops, limit, offset };
4076
4118
  if (entity) params.entity = entity;
@@ -4083,7 +4125,9 @@ var GldaiSubmodule = class {
4083
4125
  * minLat/minLng/maxLat/maxLng (the bbox), entityType (deposit|infrastructure|company|project — default
4084
4126
  * all four), energy (default false), includeCountryCentroids (default false). AGENT KEYS ONLY; metered
4085
4127
  * against the CALLING agent's wallet (quote with billingQuote); pins do NOT count against your entity
4086
- * cap. Same as the MCP `map_viewport` tool. Use this — the old /mapdata bulk surface is CLOSED. */
4128
+ * cap. Response: top-level charged_joules (= price.charged_joules; the price block stays as the breakdown) +
4129
+ * the metering block (file header). Same as the MCP `map_viewport` tool. Use this — the old /mapdata bulk
4130
+ * surface is CLOSED. */
4087
4131
  mapViewport({
4088
4132
  minLat,
4089
4133
  minLng,
@@ -4102,6 +4146,42 @@ var GldaiSubmodule = class {
4102
4146
  if (entityType != null) params.entity_type = entityType;
4103
4147
  return this._t.request(this._base, "GET", "/api/v1/map.viewport", { params, idempotencyKey });
4104
4148
  }
4149
+ /** GET /api/v1/look.at — a Sentinel-2 satellite STILL of a point (lat+lng) or an entity (entityType+id).
4150
+ * AGENT KEYS ONLY (a browser session or plain developer key is refused before any charge). Metered
4151
+ * against the CALLING agent's wallet — its own price line (~150 J; quote with
4152
+ * billingQuote("/api/v1/look.at")). On a hit returns { available: true, content_type: "image/jpeg",
4153
+ * image_jpeg: Uint8Array, provenance: { X-* headers — scene date, source, … } }; on a cloudy/missing
4154
+ * scene a { available: false, … } object carrying charged_joules (0 — the charge is refunded server-side;
4155
+ * the price block stays as the breakdown) + the metering block; on the image path the same facts ride the
4156
+ * provenance headers (X-Price-Charged-Joules, X-Metering-Attempt, X-Metering-Status). Same as the MCP
4157
+ * `look_at` tool. */
4158
+ async lookAt({ lat, lng, entityType, id, idempotencyKey } = {}) {
4159
+ const params = {};
4160
+ if (lat != null) params.lat = lat;
4161
+ if (lng != null) params.lng = lng;
4162
+ if (entityType != null) params.entity_type = entityType;
4163
+ if (id != null) params.id = id;
4164
+ const r = await this._t.request(
4165
+ this._base,
4166
+ "GET",
4167
+ "/api/v1/look.at",
4168
+ { params, idempotencyKey, accept: "image/jpeg, application/json", raw: true }
4169
+ );
4170
+ if (r && r._raw) {
4171
+ return { available: true, content_type: r.content_type, image_jpeg: r.content, provenance: r.provenance || {} };
4172
+ }
4173
+ return r;
4174
+ }
4175
+ /** YOUR OWN metered-read charge record — GET /api/v1/billing/attempts. Own wallet only (from your
4176
+ * credential, never a parameter). FREE. Each attempt shows reserved vs settled joules so you can verify
4177
+ * your bill without asking us (settle_dead_end = nothing moved — a 4xx/5xx or refused reservation;
4178
+ * settle_failed = delivered but unsettled). Parity with the MCP `billing_attempts` tool. */
4179
+ billingAttempts({ limit, offset } = {}) {
4180
+ const params = {};
4181
+ if (limit != null) params.limit = limit;
4182
+ if (offset != null) params.offset = offset;
4183
+ return this._t.request(this._base, "GET", "/api/v1/billing/attempts", { params });
4184
+ }
4105
4185
  // ── contributor-programme reads (P-DAY.105) ──────────────────────
4106
4186
  /** Your Bridge record (session): contribution units at your standing's weight, plus promoted work. */
4107
4187
  agentBridge() {
@@ -4196,7 +4276,9 @@ var JoulepaiSubmodule = class {
4196
4276
  if (handle) body.handle = handle;
4197
4277
  return this._t.request(this._base, "POST", "/wallet/create", { body });
4198
4278
  }
4199
- /** Absorbs pay() (index.js:117). ENFORCED class D — dispatch auto-generates the key. */
4279
+ /** Absorbs pay() (index.js:117). ENFORCED class D — dispatch auto-generates the key. If you pass your own
4280
+ * idempotencyKey, never a settlement-shaped one (release|refund|dispute_release|dispute_split:<match_id>:...)
4281
+ * — the backend refuses those 403 unless the caller is the marketplace service; use a fresh opaque key. */
4200
4282
  async transfer(destination, amount, {
4201
4283
  platform = "rareeai",
4202
4284
  note,
@@ -4216,10 +4298,34 @@ var JoulepaiSubmodule = class {
4216
4298
  pay(...args) {
4217
4299
  return this.transfer(...args);
4218
4300
  }
4301
+ /** Status of ONE transfer — GET /wallet/transfer/{id}/status. PARTY-TO-THE-LEG: you see only a transfer
4302
+ * you're a party to (e.g. your own deposit into a trade), NOT the trade's other legs. For the whole
4303
+ * trade's settlement (payout, fees, refunds across every leg) use tradeSettlement(matchId). */
4219
4304
  transferStatus(transferId) {
4220
4305
  return this._t.request(this._base, "GET", "/wallet/transfer/{tid}/status", { pathParams: { tid: transferId } });
4221
4306
  }
4222
- /** Absorbs fund() (index.js:152). NOT retry-safe (G1 demotion — duplicate Stripe sessions). */
4307
+ /** YOUR OWN trade's settlement — every leg of a marketplace trade you were the BUYER or SELLER of
4308
+ * (GET /wallet/trade/{matchId}/settlement). Party-gated: 404 if you were not a party (which also hides
4309
+ * whether the match exists). Returns { your_role (buyer|seller), settled (true once the provider is paid),
4310
+ * leg_count, legs[] } where each leg is { type, recipient_role (a ROLE — provider/oracle/treasury/
4311
+ * fee-collection/buyer, NEVER a wallet id; the sentinel "unknown" marks a leg type the backend does not
4312
+ * map yet — logged loudly on their side, never money to the platform), amount, status, txid, anchor }; plus
4313
+ * top-level all_anchored (bool). status is the LEDGER state of the leg; txid is written at BROADCAST, not
4314
+ * confirmation — a leg can be settled with txid null (not broadcast yet, OR the anchor dead-lettered) or
4315
+ * carry a txid not yet on chain. anchor is the state to act on: queued | confirming | confirmed → poll
4316
+ * (~30 s; txid may be null while queued); anchored → verify via the PUBLIC GET /transfer/{transfer_id}/proof;
4317
+ * failed | cancelled → the ledger leg settled but the anchor dead-lettered and will NOT reach the chain by
4318
+ * itself (escalate); none → no anchor attempted; unknown → a queue status the view does not recognise. A null
4319
+ * txid on a fresh read is NOT a missing or failed leg — read anchor. The trade-WIDE view — transferStatus()
4320
+ * and depositStatus() show only your own leg. Parity with the MCP `trade_settlement` tool. Backend d9a8e60. */
4321
+ tradeSettlement(matchId) {
4322
+ return this._t.request(this._base, "GET", "/wallet/trade/{mid}/settlement", { pathParams: { mid: matchId } });
4323
+ }
4324
+ /** FIAT/CARD funding — POST /wallet/fund. method="stripe" returns a Stripe Checkout URL for a human to
4325
+ * complete (card; 3.5% markup; amountFiat 10-100). The backend also accepts method="usdc" (1% markup),
4326
+ * but the IN-BAND AGENT USDC rail is the deposit-address flow, NOT this endpoint: an agent funds by
4327
+ * depositing USDC to its own Base address — use fundingPrepare() for the address + live availability and
4328
+ * depositStatus() to track the credit. NOT retry-safe (G1 demotion — duplicate Stripe sessions). */
4223
4329
  async fund(amountFiat, { method = "stripe" } = {}) {
4224
4330
  return this._t.request(
4225
4331
  this._base,
@@ -4314,6 +4420,47 @@ var JoulepaiSubmodule = class {
4314
4420
  fundingStatus(fundingEventId) {
4315
4421
  return this._t.request(this._base, "GET", "/wallet/fund/{fid}", { pathParams: { fid: fundingEventId } });
4316
4422
  }
4423
+ /** YOUR OWN USDC-on-Base deposit state — GET /wallet/deposit-status. Own wallet only (from your token,
4424
+ * never a parameter). Read-only, free. Returns { usdc_live, scanner_cursor_block, minimum_usdc,
4425
+ * deposits[], held_below_min_total_usdc, needed_to_credit_usdc, note }; each deposit carries { tx_hash,
4426
+ * block_number, usdc_amount, status, joules_credited, fee_taken, created_at, meaning }. A deposit whose
4427
+ * block_number is ABOVE scanner_cursor_block has not been reached yet (normal lag), not lost. 503 when
4428
+ * USDC-on-Base is not live. Parity with the MCP `deposit_status` tool. */
4429
+ depositStatus() {
4430
+ return this._t.request(this._base, "GET", "/wallet/deposit-status", {});
4431
+ }
4432
+ /** The in-band funding step for a joule shortfall — NEVER a URL to visit (operator lock). USDC on Base is
4433
+ * the live agent-fundable rail: deposit USDC to your own Base address (min 5 USDC — the authoritative
4434
+ * value is depositStatus().minimum_usdc), credited automatically when the scanner sees it (track with
4435
+ * depositStatus()). Card funding stays a human web flow. Availability is read LIVE (relays your
4436
+ * deposit-address) so it never reports stale state; it does not itself move money. Parity with the MCP
4437
+ * `funding_prepare` tool. Returns { needed, in_band_agent_funding_live, routes, note }. */
4438
+ async fundingPrepare(needed = 0) {
4439
+ let live = true, address = null;
4440
+ try {
4441
+ const addr = await this.depositAddress();
4442
+ address = addr && typeof addr === "object" ? addr.address ?? null : null;
4443
+ } catch (err) {
4444
+ if (err instanceof GreenlandAIError) {
4445
+ live = false;
4446
+ address = null;
4447
+ } else throw err;
4448
+ }
4449
+ return {
4450
+ needed: Number(needed),
4451
+ in_band_agent_funding_live: live,
4452
+ routes: {
4453
+ usdc_on_base: {
4454
+ status: live ? "live" : "not_live",
4455
+ deposit_address: address,
4456
+ minimum_usdc: 5,
4457
+ note: live ? "deposit USDC to this Base address; credited automatically within the scanner window; check with depositStatus()" : "no in-band USDC address for this credential right now \u2014 authenticate with your wallet credential, or fund with card meanwhile"
4458
+ },
4459
+ card_stripe: { status: "human_web_only", note: "not an agent/in-band path" }
4460
+ },
4461
+ 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."
4462
+ };
4463
+ }
4317
4464
  resetCredentials(walletId, email) {
4318
4465
  return this._t.request(
4319
4466
  this._base,
@@ -4359,16 +4506,73 @@ var JoulepaiSubmodule = class {
4359
4506
  // src/rareeai.js
4360
4507
  var RAREEAI_BASE = "https://greenlandai.ai";
4361
4508
  var RAREEAI_PREFIX = "/api/v1/marketplace";
4362
- var RareeaiSubmodule = class {
4509
+ var RareeaiSubmodule = class _RareeaiSubmodule {
4363
4510
  constructor(transport, baseUrl = RAREEAI_BASE) {
4364
4511
  this._t = transport;
4365
4512
  this._base = baseUrl;
4366
4513
  this._p = RAREEAI_PREFIX;
4367
4514
  }
4515
+ // Body field lists = the backend models (rareeai schemas.py: ProviderCreate / RequestCreate /
4516
+ // DisputeCreate / ResolveCreate; deliver, approve, reject, extend-dispute take NO body — their inputs
4517
+ // are path/query). Extra keys are refused HERE with a clear error rather than sent: the backend is
4518
+ // moving to strict models, and a silently-dropped or 422'd key is worse than a TypeError.
4519
+ static BODY_FIELDS = {
4520
+ provide: /* @__PURE__ */ new Set([
4521
+ "wallet_id",
4522
+ "frontier",
4523
+ "resource_type",
4524
+ "unit_type",
4525
+ "price_joules_per_unit",
4526
+ "capacity_total",
4527
+ "min_units",
4528
+ "max_units_per_match",
4529
+ "endpoint_url",
4530
+ "sla",
4531
+ "speed",
4532
+ "timeout_hours",
4533
+ "timeout_minutes",
4534
+ "stake_amount",
4535
+ "oracle_verified",
4536
+ "idempotency_key"
4537
+ ]),
4538
+ request: /* @__PURE__ */ new Set([
4539
+ "wallet_id",
4540
+ "frontier",
4541
+ "resource_type",
4542
+ "unit_type",
4543
+ "units_needed",
4544
+ "max_price_per_unit",
4545
+ "priority",
4546
+ "requirements",
4547
+ "ttl_seconds",
4548
+ "speed",
4549
+ "privacy_mode",
4550
+ "contract_escrow",
4551
+ "idempotency_key"
4552
+ ]),
4553
+ dispute: /* @__PURE__ */ new Set(["reason"]),
4554
+ resolve: /* @__PURE__ */ new Set(["resolution", "split_pct"]),
4555
+ deliver: /* @__PURE__ */ new Set(),
4556
+ approve: /* @__PURE__ */ new Set(),
4557
+ reject: /* @__PURE__ */ new Set(),
4558
+ extend_dispute: /* @__PURE__ */ new Set()
4559
+ };
4560
+ /** Keep only fields the backend model for `kind` accepts; refuse the rest by name. */
4561
+ static _body(kind, fields) {
4562
+ const allowed = _RareeaiSubmodule.BODY_FIELDS[kind];
4563
+ const bad = Object.keys(fields || {}).filter((k) => !allowed.has(k)).sort();
4564
+ if (bad.length) {
4565
+ throw new TypeError(`${kind}: unknown field(s) ${JSON.stringify(bad)}; allowed: ${allowed.size ? JSON.stringify([...allowed].sort()) : "none (no request body)"}`);
4566
+ }
4567
+ return { ...fields || {} };
4568
+ }
4368
4569
  // Pattern B
4369
- createProvider({ resourceType, capacity, idempotencyKey, retry = true, ...fields }) {
4370
- const body = { resource_type: resourceType, ...fields };
4371
- if (capacity) body.capacity = capacity;
4570
+ /** `capacityTotal` is the backend field (units on offer); `capacity` is a deprecated alias — earlier
4571
+ * SDKs sent a `capacity` key the backend never read. */
4572
+ createProvider({ resourceType, capacityTotal, capacity, idempotencyKey, retry = true, ...fields }) {
4573
+ const body = { resource_type: resourceType, ..._RareeaiSubmodule._body("provide", fields) };
4574
+ const cap = capacityTotal ?? capacity;
4575
+ if (cap != null) body.capacity_total = cap;
4372
4576
  return this._t.request(this._base, "POST", `${this._p}/provide`, { body, idempotencyKey, retry });
4373
4577
  }
4374
4578
  // ENFORCED-WHEN-PRESENT / BEST-EFFORT-keyless (routes.py:1282 guard; SDK dispatch
@@ -4378,7 +4582,7 @@ var RareeaiSubmodule = class {
4378
4582
  this._base,
4379
4583
  "POST",
4380
4584
  `${this._p}/request`,
4381
- { body: { resource_type: resourceType, ...fields }, idempotencyKey, retry }
4585
+ { body: { resource_type: resourceType, ..._RareeaiSubmodule._body("request", fields) }, idempotencyKey, retry }
4382
4586
  );
4383
4587
  }
4384
4588
  // 0.3.3: delivery enters the post-delivery hold (no inline release); the
@@ -4395,7 +4599,7 @@ var RareeaiSubmodule = class {
4395
4599
  `${this._p}/deliver/{match_id}`,
4396
4600
  {
4397
4601
  pathParams: { match_id: matchId },
4398
- body: fields,
4602
+ body: _RareeaiSubmodule._body("deliver", fields),
4399
4603
  params: Object.keys(params).length ? params : void 0,
4400
4604
  idempotencyKey,
4401
4605
  retry
@@ -4417,7 +4621,7 @@ var RareeaiSubmodule = class {
4417
4621
  this._base,
4418
4622
  "POST",
4419
4623
  `${this._p}/match/{match_id}/resolve`,
4420
- { pathParams: { match_id: matchId }, body: fields, idempotencyKey, retry }
4624
+ { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("resolve", fields), idempotencyKey, retry }
4421
4625
  );
4422
4626
  }
4423
4627
  // FSM transitions — NOT SUPPORTED (auto-retry OFF)
@@ -4426,7 +4630,7 @@ var RareeaiSubmodule = class {
4426
4630
  this._base,
4427
4631
  "POST",
4428
4632
  `${this._p}/match/{match_id}/approve`,
4429
- { pathParams: { match_id: matchId }, body: fields }
4633
+ { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("approve", fields) }
4430
4634
  );
4431
4635
  }
4432
4636
  reject(matchId, fields = {}) {
@@ -4434,7 +4638,7 @@ var RareeaiSubmodule = class {
4434
4638
  this._base,
4435
4639
  "POST",
4436
4640
  `${this._p}/match/{match_id}/reject`,
4437
- { pathParams: { match_id: matchId }, body: fields }
4641
+ { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("reject", fields) }
4438
4642
  );
4439
4643
  }
4440
4644
  dispute(matchId, fields = {}) {
@@ -4442,7 +4646,7 @@ var RareeaiSubmodule = class {
4442
4646
  this._base,
4443
4647
  "POST",
4444
4648
  `${this._p}/match/{match_id}/dispute`,
4445
- { pathParams: { match_id: matchId }, body: fields }
4649
+ { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("dispute", fields) }
4446
4650
  );
4447
4651
  }
4448
4652
  extendDispute(matchId, fields = {}) {
@@ -4450,7 +4654,7 @@ var RareeaiSubmodule = class {
4450
4654
  this._base,
4451
4655
  "POST",
4452
4656
  `${this._p}/match/{match_id}/extend-dispute`,
4453
- { pathParams: { match_id: matchId }, body: fields }
4657
+ { pathParams: { match_id: matchId }, body: _RareeaiSubmodule._body("extend_dispute", fields) }
4454
4658
  );
4455
4659
  }
4456
4660
  // reads
@@ -4521,6 +4725,10 @@ var RareeaiSubmodule = class {
4521
4725
  // 50-5,000 joules total, split across the match's oracles — deducted from the trade at
4522
4726
  // settlement. Assess within the 48-hour deadline. NOT auto-retried (no verified server
4523
4727
  // idempotency claim on this path).
4728
+ // 409 = LATE: the match already advanced (oracle_status verified/failed/disputed, or it left
4729
+ // escrowed/delivered) — your verdict is moot; do not retry, read the match. Consensus is a MAJORITY
4730
+ // of assigned oracles (floor 2), not all-must-report: once a majority lands the trade settles and
4731
+ // remaining assignments EXPIRE (a late assess then 409s).
4524
4732
  oracleAssess(matchId, { verdict, qualityScore, notes = "", executionTrace, ...fields }) {
4525
4733
  const body = { verdict, quality_score: qualityScore, notes, ...fields };
4526
4734
  if (executionTrace !== void 0) body.execution_trace = executionTrace;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@greenlandai/sdk",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "Unified SDK for the GreenlandAI ecosystem (ENYAL, JoulePAI, RAREEAI, GreenlandAI)",
5
5
  "license": "Apache-2.0",
6
- "homepage": "https://enyal.ai",
6
+ "homepage": "https://greenlandai.ai",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
@@ -44,6 +44,7 @@ export const IDEMPOTENCY_MAP = {
44
44
  "GET /api/v1/nearby": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
45
45
  "GET /api/v1/relationships": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
46
46
  "GET /api/v1/map.viewport": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
47
+ "GET /api/v1/look.at": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
47
48
  // (cf) ENYAL metered GET — joins Class C header class (server reads X-Idempotency-Key per the Option-B switch)
48
49
  "GET /api/v1/search": { field: "X-Idempotency-Key", placement: "header", tier: ENFORCED },
49
50
  // Class D — transfer-class
@@ -61,7 +61,8 @@ export class Transport {
61
61
  async request(baseUrl, method, pathTemplate,
62
62
  { pathParams = {}, body = null, params = null,
63
63
  idempotencyKey = null, retry = true,
64
- maxRetries = DEFAULT_MAX_RETRIES } = {}) {
64
+ maxRetries = DEFAULT_MAX_RETRIES,
65
+ accept = null, raw = false } = {}) {
65
66
  // Auth header by parameter (X-API-Key for apiKey incl. eyl_/gai_; Bearer for an OAuth JWT).
66
67
  // See docs/canonical/security-policy.md (X-API-Key > Bearer > cookie).
67
68
  let headers = this._isApiKey
@@ -84,7 +85,7 @@ export class Transport {
84
85
  const t0 = Date.now();
85
86
  for (;;) {
86
87
  try {
87
- const result = await this._once(method, url, headers, body);
88
+ const result = await this._once(method, url, headers, body, { accept, raw });
88
89
  this._count("sdk.requests"); this._hist("sdk.request.duration", (Date.now() - t0) / 1000);
89
90
  if (result && result.duplicate === true) {
90
91
  this._count("sdk.duplicates");
@@ -110,7 +111,7 @@ export class Transport {
110
111
  }
111
112
  }
112
113
 
113
- async _once(method, url, headers, body) {
114
+ async _once(method, url, headers, body, { accept = null, raw = false } = {}) {
114
115
  const redacted = { ...headers };
115
116
  if ("Authorization" in redacted) redacted.Authorization = "[REDACTED]";
116
117
  if ("X-API-Key" in redacted) redacted["X-API-Key"] = "[REDACTED]";
@@ -118,6 +119,7 @@ export class Transport {
118
119
  let resp;
119
120
  try {
120
121
  const opts = { method, headers: { ...headers } };
122
+ if (accept) opts.headers["Accept"] = accept;
121
123
  if (body != null) {
122
124
  opts.headers["Content-Type"] = "application/json";
123
125
  opts.body = JSON.stringify(body);
@@ -136,6 +138,17 @@ export class Transport {
136
138
  if (typeof detail === "object") detail = JSON.stringify(detail);
137
139
  throw errorForStatus(resp.status, String(detail), requestId, retryAfter);
138
140
  }
141
+ if (raw) {
142
+ // Binary-capable path (look.at: image/jpeg body, or a 200 JSON {available:false}).
143
+ const ct = resp.headers?.get ? (resp.headers.get("content-type") || "") : "";
144
+ if (ct.startsWith("application/json")) return resp.json();
145
+ const buf = await resp.arrayBuffer();
146
+ const provenance = {};
147
+ if (resp.headers?.forEach) resp.headers.forEach((v, k) => {
148
+ if (k.toLowerCase().startsWith("x-")) provenance[k] = v;
149
+ });
150
+ return { _raw: true, content_type: ct, content: new Uint8Array(buf), provenance };
151
+ }
139
152
  if (resp.status === 204) return null;
140
153
  return resp.json();
141
154
  }
package/src/gldai.js CHANGED
@@ -8,46 +8,76 @@
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
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. */
11
+ * query; helper names match the MCP tools. Nothing on this surface is MCP-only.
12
+ * METERED RESPONSES (0.5.5, backend b1b587d / 43ff414 / a3c97f9, 2026-09-22): every metered JSON response
13
+ * carries ONE top-level `charged_joules` (the all-in debit for THIS call = base + the 0.5% rail fee; the
14
+ * posed routes lookFrom / mapViewport / lookAt ALSO keep their `price` block as the breakdown, with
15
+ * price.charged_joules == charged_joules) AND a `metering` block written AFTER the settle has run:
16
+ * { attempt_id, settlement: settled | settled_zero | settle_failed | released, settled_joules (what actually
17
+ * left the wallet — 0 unless settled), check: "GET /api/v1/billing/attempts" }. Read metering.settlement,
18
+ * not charged_joules, to know whether you paid: settle_failed = delivered but unpaid (the wallet is then
19
+ * locked by the debt gate until the retry clears — the 402 you get next names the attempt, the amount and
20
+ * what clears it); settled_zero = an empty result, nothing moved. The same facts ride the headers
21
+ * X-Metering-Attempt / X-Metering-Status. billingAttempts() shows every attempt's state afterwards. */
12
22
  export const GLDAI_BASE = "https://greenlandai.ai";
13
23
 
14
24
  export class GldaiSubmodule {
15
25
  constructor(transport, baseUrl = GLDAI_BASE) {
16
26
  this._t = transport; this._base = baseUrl;
17
27
  }
28
+ /** GET /api/v1/companies (Class C, metered): charged_joules + the metering block (file header — read metering.settlement to know whether you paid). */
18
29
  companies({ idempotencyKey, ...params } = {}) {
19
30
  return this._t.request(this._base, "GET", "/api/v1/companies", { params, idempotencyKey });
20
31
  }
32
+ /** GET /api/v1/companies/{id} — metered: charged_joules + metering block (file header). */
21
33
  company(companyId) {
22
34
  return this._t.request(this._base, "GET", "/api/v1/companies/{cid}", { pathParams: { cid: companyId } });
23
35
  }
36
+ /** GET /api/v1/deposits — list resource deposits (Class C, metered). Filters via the params object
37
+ * (API names, passed through): resource_type, country, status, owner_country, max_port_km, search,
38
+ * limit (<=100), offset, and `commodity`. ⚠ `commodity` filters by the commodity GRAPH, not the
39
+ * resource_type string: it matches a deposit that CONTAINS the commodity directly, OR CONTAINS a group
40
+ * the commodity is MEMBER_OF — so commodity:"neodymium" returns EVERY rare-earth-element deposit,
41
+ * including ones whose name never says "neodymium" (it would look broken otherwise). The top-level
42
+ * `commodity_filter` {query, matched_directly, matched_via_group} tells you which (matched_via_group
43
+ * names the group). Each deposit carries `commodities[]` {name, role:primary|byproduct, group};
44
+ * resource_type stays primary. The response also carries `charged_joules` (all-in metered cost; null
45
+ * for a quota caller) and the metering block (file header). R6-C, 2026-09-22. */
24
46
  deposits({ idempotencyKey, ...params } = {}) {
25
47
  return this._t.request(this._base, "GET", "/api/v1/deposits", { params, idempotencyKey });
26
48
  }
49
+ /** GET /api/v1/deposits/{id} — metered: charged_joules + metering block (file header). */
27
50
  deposit(depositId) {
28
51
  return this._t.request(this._base, "GET", "/api/v1/deposits/{did}", { pathParams: { did: depositId } });
29
52
  }
53
+ /** GET /api/v1/infrastructure (Class C, metered): charged_joules + metering block (file header). */
30
54
  infrastructureList({ idempotencyKey, ...params } = {}) {
31
55
  return this._t.request(this._base, "GET", "/api/v1/infrastructure", { params, idempotencyKey });
32
56
  }
57
+ /** GET /api/v1/infrastructure/{id} — metered: charged_joules + metering block (file header). */
33
58
  infrastructure(infraId) {
34
59
  return this._t.request(this._base, "GET", "/api/v1/infrastructure/{iid}", { pathParams: { iid: infraId } });
35
60
  }
36
- /** GET /api/v1/query — the natural-language intelligence query, metered per call (Class C). WORKS FOR
37
- * JOULE-METERED AGENTS: they pay per query and are EXEMPT from the human NL access gates (the old
38
- * charged-then-403 for agents was fixed; api.py:1414 `_is_joule_agent` bypasses the email-verify /
39
- * door / entitlement checks, which apply to human accounts only). Humans need a verified ENYAL
40
- * identity + NL access ($10/level). Metered against the CALLING agent's wallet — quote with
41
- * billingQuote("/api/v1/query") first. */
61
+ /** GET /api/v1/query — the natural-language intelligence query. CLOSED TO ALL CALLERS TODAY (2026-09-22,
62
+ * operator ruling): to agents by the August 2026 ruling (not part of the agent launch — the meter refuses
63
+ * an agent 403 BEFORE any charge), to human sessions on capacity grounds (HUMAN_QUERY_ENABLED). It reopens
64
+ * when there are servers for it. Nothing is charged for a refused call. Use the structured surface instead:
65
+ * companies / deposits / infrastructure / projects / relationships / lookFrom / nearby / mapViewport. Kept
66
+ * so the method resolves; matches the served llms.txt and spec. */
42
67
  query(q, { idempotencyKey, ...params } = {}) {
43
68
  return this._t.request(this._base, "GET", "/api/v1/query", { params: { q, ...params }, idempotencyKey });
44
69
  }
70
+ /** GET /api/v1/projects (Class C, metered): charged_joules + metering block (file header). */
45
71
  projects({ idempotencyKey, ...params } = {}) {
46
72
  return this._t.request(this._base, "GET", "/api/v1/projects", { params, idempotencyKey });
47
73
  }
74
+ /** GET /api/v1/projects/{id} — metered: charged_joules + metering block (file header). */
48
75
  project(projectId) {
49
76
  return this._t.request(this._base, "GET", "/api/v1/projects/{pid}", { pathParams: { pid: projectId } });
50
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). */
51
81
  mapdata({ idempotencyKey, ...params } = {}) {
52
82
  return this._t.request(this._base, "GET", "/api/v1/mapdata", { params, idempotencyKey });
53
83
  }
@@ -56,7 +86,8 @@ export class GldaiSubmodule {
56
86
  /** The exact per-caller price of a metered call BEFORE you make it — GET /api/v1/billing/quote. FREE
57
87
  * (no charge), needs only a credential (no verification). `path` = the API path the call would hit
58
88
  * (e.g. "/api/v1/relationships", "/api/v1/look.from", "/api/v1/nearby", "/api/v1/companies/{id}",
59
- * "/api/v1/mapdata"); `hops` = graph depth 1-20 for a relationships path. Priced at YOUR tier.
89
+ * "/api/v1/mapdata"); `hops` = graph depth 1-10 (your tier caps it — Pioneer/FC 3, TEN/Pro 5,
90
+ * Enterprise 10) for a relationships path. Priced at YOUR tier.
60
91
  * Returns { joules (base), rail_fee_joules, joules_all_in, pricing_tier, usd, … } — joules_all_in is
61
92
  * the TRUE debit (base + the 0.5% rail surcharge), so fund THAT, not the base. Same helper as the MCP
62
93
  * `billing_quote` tool. Metered reads debit the CALLING agent's OWN wallet (not the owner's); read the
@@ -69,7 +100,9 @@ export class GldaiSubmodule {
69
100
  * (entityType+id). Metered against the CALLING agent's wallet (base + 0.5% rail; quote with
70
101
  * billingQuote). entityType behaves two ways (backend 2026-09-14): entityType ALONE (with lat/lng)
71
102
  * FILTERS the frame to that type; entityType + id ANCHORS the pose at that entity and keeps ALL types;
72
- * an unknown entityType is a 400 before any charge. Same as the MCP `look_from` tool. */
103
+ * an unknown entityType is a 400 before any charge. Response: top-level charged_joules (the all-in debit —
104
+ * the same figure as price.charged_joules; the price block stays as the breakdown) + the metering block
105
+ * (file header). Same as the MCP `look_from` tool. */
73
106
  lookFrom({ lat, lng, entityType, id, radiusKm = 100, energy = false,
74
107
  includeCountryCentroids = false, idempotencyKey } = {}) {
75
108
  const params = { radius_km: radiusKm, energy, include_country_centroids: includeCountryCentroids };
@@ -80,7 +113,8 @@ export class GldaiSubmodule {
80
113
  return this._t.request(this._base, "GET", "/api/v1/look.from", { params, idempotencyKey });
81
114
  }
82
115
  /** GET /api/v1/nearby — entities near a location; here entityType IS a content filter. Metered against
83
- * the CALLING agent's wallet (quote with billingQuote). Same as the MCP `nearby` tool. */
116
+ * the CALLING agent's wallet (quote with billingQuote): charged_joules + metering block (file header).
117
+ * Same as the MCP `nearby` tool. */
84
118
  nearby({ lat, lng, radiusKm = 100, entityType, limit = 20,
85
119
  includeCountryCentroids = false, idempotencyKey } = {}) {
86
120
  const params = { lat, lng, radius_km: radiusKm, limit, include_country_centroids: includeCountryCentroids };
@@ -89,8 +123,12 @@ export class GldaiSubmodule {
89
123
  }
90
124
  /** GET /api/v1/relationships — labelled relationship hops (the MCP `hops` tool). `entity` is the START
91
125
  * NODE, matched as a case-insensitive SUBSTRING of an entity NAME (never an id: "3" matches any name
92
- * containing "3"), so pass a full, distinctive name. `hops` = depth 1-10. Metered per hop against the
93
- * CALLING agent's wallet (quote with billingQuote("/api/v1/relationships", n)). */
126
+ * containing "3"), so pass a full, distinctive name. `hops` = depth 1-10. relationType (one relation label,
127
+ * e.g. OPERATES, CONTAINS, MEMBER_OF) is checked against the API's allow-list on BOTH paths (with or without
128
+ * entity, backend a3c97f9): an unknown label is a 400 naming the allowed set, BEFORE any charge — never an
129
+ * empty 200. Metered per hop against the CALLING agent's wallet (quote with
130
+ * billingQuote("/api/v1/relationships", n)): the response carries charged_joules (the settled all-in — 0 for
131
+ * an empty result) + the metering block (file header). */
94
132
  relationships({ entity, hops = 1, relationType, search, limit = 50, offset = 0, idempotencyKey } = {}) {
95
133
  const params = { hops, limit, offset };
96
134
  if (entity) params.entity = entity;
@@ -103,7 +141,9 @@ export class GldaiSubmodule {
103
141
  * minLat/minLng/maxLat/maxLng (the bbox), entityType (deposit|infrastructure|company|project — default
104
142
  * all four), energy (default false), includeCountryCentroids (default false). AGENT KEYS ONLY; metered
105
143
  * against the CALLING agent's wallet (quote with billingQuote); pins do NOT count against your entity
106
- * cap. Same as the MCP `map_viewport` tool. Use this — the old /mapdata bulk surface is CLOSED. */
144
+ * 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. */
107
147
  mapViewport({ minLat, minLng, maxLat, maxLng, entityType, energy = false,
108
148
  includeCountryCentroids = false, idempotencyKey } = {}) {
109
149
  const params = { energy, include_country_centroids: includeCountryCentroids };
@@ -114,6 +154,38 @@ export class GldaiSubmodule {
114
154
  if (entityType != null) params.entity_type = entityType;
115
155
  return this._t.request(this._base, "GET", "/api/v1/map.viewport", { params, idempotencyKey });
116
156
  }
157
+ /** GET /api/v1/look.at — a Sentinel-2 satellite STILL of a point (lat+lng) or an entity (entityType+id).
158
+ * AGENT KEYS ONLY (a browser session or plain developer key is refused before any charge). Metered
159
+ * against the CALLING agent's wallet — its own price line (~150 J; quote with
160
+ * billingQuote("/api/v1/look.at")). On a hit returns { available: true, content_type: "image/jpeg",
161
+ * image_jpeg: Uint8Array, provenance: { X-* headers — scene date, source, … } }; on a cloudy/missing
162
+ * scene a { available: false, … } object carrying charged_joules (0 — the charge is refunded server-side;
163
+ * the price block stays as the breakdown) + the metering block; on the image path the same facts ride the
164
+ * provenance headers (X-Price-Charged-Joules, X-Metering-Attempt, X-Metering-Status). Same as the MCP
165
+ * `look_at` tool. */
166
+ async lookAt({ lat, lng, entityType, id, idempotencyKey } = {}) {
167
+ const params = {};
168
+ if (lat != null) params.lat = lat;
169
+ if (lng != null) params.lng = lng;
170
+ if (entityType != null) params.entity_type = entityType;
171
+ if (id != null) params.id = id;
172
+ const r = await this._t.request(this._base, "GET", "/api/v1/look.at",
173
+ { params, idempotencyKey, accept: "image/jpeg, application/json", raw: true });
174
+ if (r && r._raw) {
175
+ return { available: true, content_type: r.content_type, image_jpeg: r.content, provenance: r.provenance || {} };
176
+ }
177
+ return r; // a 200 JSON { available: false, … } passes straight through
178
+ }
179
+ /** YOUR OWN metered-read charge record — GET /api/v1/billing/attempts. Own wallet only (from your
180
+ * credential, never a parameter). FREE. Each attempt shows reserved vs settled joules so you can verify
181
+ * your bill without asking us (settle_dead_end = nothing moved — a 4xx/5xx or refused reservation;
182
+ * settle_failed = delivered but unsettled). Parity with the MCP `billing_attempts` tool. */
183
+ billingAttempts({ limit, offset } = {}) {
184
+ const params = {};
185
+ if (limit != null) params.limit = limit;
186
+ if (offset != null) params.offset = offset;
187
+ return this._t.request(this._base, "GET", "/api/v1/billing/attempts", { params });
188
+ }
117
189
 
118
190
  // ── contributor-programme reads (P-DAY.105) ──────────────────────
119
191
  /** Your Bridge record (session): contribution units at your standing's weight, plus promoted work. */
package/src/joulepai.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * Source-of-record: local joulepai-sdk-js/index.js (never published).
3
3
  * Transfer-class now carries Class-D keys via dispatch (the local SDK sent none). */
4
4
  import { GLDAI_BASE } from "./gldai.js"; // reuse the single greenlandai.ai base for the agent-self balance route
5
+ import { GreenlandAIError } from "./core/errors.js";
5
6
 
6
7
  export const JOULEPAI_BASE = "https://joulepai.ai/api/v1";
7
8
 
@@ -28,7 +29,9 @@ export class JoulepaiSubmodule {
28
29
  return this._t.request(this._base, "POST", "/wallet/create", { body });
29
30
  }
30
31
 
31
- /** Absorbs pay() (index.js:117). ENFORCED class D — dispatch auto-generates the key. */
32
+ /** Absorbs pay() (index.js:117). ENFORCED class D — dispatch auto-generates the key. If you pass your own
33
+ * idempotencyKey, never a settlement-shaped one (release|refund|dispute_release|dispute_split:<match_id>:...)
34
+ * — the backend refuses those 403 unless the caller is the marketplace service; use a fresh opaque key. */
32
35
  async transfer(destination, amount, { platform = "rareeai", note, privacyMode,
33
36
  registrationId, idempotencyKey, retry = true } = {}) {
34
37
  const body = { from_wallet_id: await this._ensureId(), amount, platform };
@@ -42,11 +45,36 @@ export class JoulepaiSubmodule {
42
45
 
43
46
  pay(...args) { return this.transfer(...args); }
44
47
 
48
+ /** Status of ONE transfer — GET /wallet/transfer/{id}/status. PARTY-TO-THE-LEG: you see only a transfer
49
+ * you're a party to (e.g. your own deposit into a trade), NOT the trade's other legs. For the whole
50
+ * trade's settlement (payout, fees, refunds across every leg) use tradeSettlement(matchId). */
45
51
  transferStatus(transferId) {
46
52
  return this._t.request(this._base, "GET", "/wallet/transfer/{tid}/status", { pathParams: { tid: transferId } });
47
53
  }
48
54
 
49
- /** Absorbs fund() (index.js:152). NOT retry-safe (G1 demotion — duplicate Stripe sessions). */
55
+ /** YOUR OWN trade's settlement — every leg of a marketplace trade you were the BUYER or SELLER of
56
+ * (GET /wallet/trade/{matchId}/settlement). Party-gated: 404 if you were not a party (which also hides
57
+ * whether the match exists). Returns { your_role (buyer|seller), settled (true once the provider is paid),
58
+ * leg_count, legs[] } where each leg is { type, recipient_role (a ROLE — provider/oracle/treasury/
59
+ * fee-collection/buyer, NEVER a wallet id; the sentinel "unknown" marks a leg type the backend does not
60
+ * map yet — logged loudly on their side, never money to the platform), amount, status, txid, anchor }; plus
61
+ * top-level all_anchored (bool). status is the LEDGER state of the leg; txid is written at BROADCAST, not
62
+ * confirmation — a leg can be settled with txid null (not broadcast yet, OR the anchor dead-lettered) or
63
+ * carry a txid not yet on chain. anchor is the state to act on: queued | confirming | confirmed → poll
64
+ * (~30 s; txid may be null while queued); anchored → verify via the PUBLIC GET /transfer/{transfer_id}/proof;
65
+ * failed | cancelled → the ledger leg settled but the anchor dead-lettered and will NOT reach the chain by
66
+ * itself (escalate); none → no anchor attempted; unknown → a queue status the view does not recognise. A null
67
+ * txid on a fresh read is NOT a missing or failed leg — read anchor. The trade-WIDE view — transferStatus()
68
+ * and depositStatus() show only your own leg. Parity with the MCP `trade_settlement` tool. Backend d9a8e60. */
69
+ tradeSettlement(matchId) {
70
+ return this._t.request(this._base, "GET", "/wallet/trade/{mid}/settlement", { pathParams: { mid: matchId } });
71
+ }
72
+
73
+ /** FIAT/CARD funding — POST /wallet/fund. method="stripe" returns a Stripe Checkout URL for a human to
74
+ * complete (card; 3.5% markup; amountFiat 10-100). The backend also accepts method="usdc" (1% markup),
75
+ * but the IN-BAND AGENT USDC rail is the deposit-address flow, NOT this endpoint: an agent funds by
76
+ * depositing USDC to its own Base address — use fundingPrepare() for the address + live availability and
77
+ * depositStatus() to track the credit. NOT retry-safe (G1 demotion — duplicate Stripe sessions). */
50
78
  async fund(amountFiat, { method = "stripe" } = {}) {
51
79
  return this._t.request(this._base, "POST", "/wallet/fund",
52
80
  { body: { wallet_id: await this._ensureId(), amount_fiat: amountFiat, method } });
@@ -120,6 +148,49 @@ export class JoulepaiSubmodule {
120
148
  return this._t.request(this._base, "GET", "/wallet/fund/{fid}", { pathParams: { fid: fundingEventId } });
121
149
  }
122
150
 
151
+ /** YOUR OWN USDC-on-Base deposit state — GET /wallet/deposit-status. Own wallet only (from your token,
152
+ * never a parameter). Read-only, free. Returns { usdc_live, scanner_cursor_block, minimum_usdc,
153
+ * deposits[], held_below_min_total_usdc, needed_to_credit_usdc, note }; each deposit carries { tx_hash,
154
+ * block_number, usdc_amount, status, joules_credited, fee_taken, created_at, meaning }. A deposit whose
155
+ * block_number is ABOVE scanner_cursor_block has not been reached yet (normal lag), not lost. 503 when
156
+ * USDC-on-Base is not live. Parity with the MCP `deposit_status` tool. */
157
+ depositStatus() { return this._t.request(this._base, "GET", "/wallet/deposit-status", {}); }
158
+
159
+ /** The in-band funding step for a joule shortfall — NEVER a URL to visit (operator lock). USDC on Base is
160
+ * the live agent-fundable rail: deposit USDC to your own Base address (min 5 USDC — the authoritative
161
+ * value is depositStatus().minimum_usdc), credited automatically when the scanner sees it (track with
162
+ * depositStatus()). Card funding stays a human web flow. Availability is read LIVE (relays your
163
+ * deposit-address) so it never reports stale state; it does not itself move money. Parity with the MCP
164
+ * `funding_prepare` tool. Returns { needed, in_band_agent_funding_live, routes, note }. */
165
+ async fundingPrepare(needed = 0) {
166
+ let live = true, address = null;
167
+ try {
168
+ const addr = await this.depositAddress();
169
+ address = addr && typeof addr === "object" ? addr.address ?? null : null;
170
+ } catch (err) {
171
+ if (err instanceof GreenlandAIError) { live = false; address = null; }
172
+ else throw err;
173
+ }
174
+ return {
175
+ needed: Number(needed),
176
+ in_band_agent_funding_live: live,
177
+ routes: {
178
+ usdc_on_base: {
179
+ status: live ? "live" : "not_live",
180
+ deposit_address: address,
181
+ minimum_usdc: 5,
182
+ note: live
183
+ ? "deposit USDC to this Base address; credited automatically within the scanner window; check with depositStatus()"
184
+ : "no in-band USDC address for this credential right now — authenticate with your wallet credential, or fund with card meanwhile",
185
+ },
186
+ card_stripe: { status: "human_web_only", note: "not an agent/in-band path" },
187
+ },
188
+ note: live
189
+ ? "USDC on Base is live — deposit to your Base address above (min 5 USDC), credited automatically; track it with depositStatus(). Do not follow a URL to fund."
190
+ : "No in-band USDC address available for this credential; fund with card meanwhile. Do not follow a URL to fund.",
191
+ };
192
+ }
193
+
123
194
  resetCredentials(walletId, email) {
124
195
  return this._t.request(this._base, "POST", "/wallet/reset-credentials",
125
196
  { body: { wallet_id: walletId, email } });
package/src/rareeai.js CHANGED
@@ -34,17 +34,45 @@ export class RareeaiSubmodule {
34
34
  this._t = transport; this._base = baseUrl; this._p = RAREEAI_PREFIX;
35
35
  }
36
36
 
37
+ // Body field lists = the backend models (rareeai schemas.py: ProviderCreate / RequestCreate /
38
+ // DisputeCreate / ResolveCreate; deliver, approve, reject, extend-dispute take NO body — their inputs
39
+ // are path/query). Extra keys are refused HERE with a clear error rather than sent: the backend is
40
+ // moving to strict models, and a silently-dropped or 422'd key is worse than a TypeError.
41
+ static BODY_FIELDS = {
42
+ provide: new Set(["wallet_id", "frontier", "resource_type", "unit_type", "price_joules_per_unit",
43
+ "capacity_total", "min_units", "max_units_per_match", "endpoint_url", "sla", "speed",
44
+ "timeout_hours", "timeout_minutes", "stake_amount", "oracle_verified", "idempotency_key"]),
45
+ request: new Set(["wallet_id", "frontier", "resource_type", "unit_type", "units_needed",
46
+ "max_price_per_unit", "priority", "requirements", "ttl_seconds", "speed", "privacy_mode",
47
+ "contract_escrow", "idempotency_key"]),
48
+ dispute: new Set(["reason"]),
49
+ resolve: new Set(["resolution", "split_pct"]),
50
+ deliver: new Set(), approve: new Set(), reject: new Set(), extend_dispute: new Set(),
51
+ };
52
+ /** Keep only fields the backend model for `kind` accepts; refuse the rest by name. */
53
+ static _body(kind, fields) {
54
+ const allowed = RareeaiSubmodule.BODY_FIELDS[kind];
55
+ const bad = Object.keys(fields || {}).filter((k) => !allowed.has(k)).sort();
56
+ if (bad.length) {
57
+ throw new TypeError(`${kind}: unknown field(s) ${JSON.stringify(bad)}; allowed: ${allowed.size ? JSON.stringify([...allowed].sort()) : "none (no request body)"}`);
58
+ }
59
+ return { ...(fields || {}) };
60
+ }
61
+
37
62
  // Pattern B
38
- createProvider({ resourceType, capacity, idempotencyKey, retry = true, ...fields }) {
39
- const body = { resource_type: resourceType, ...fields };
40
- if (capacity) body.capacity = capacity;
63
+ /** `capacityTotal` is the backend field (units on offer); `capacity` is a deprecated alias — earlier
64
+ * SDKs sent a `capacity` key the backend never read. */
65
+ createProvider({ resourceType, capacityTotal, capacity, idempotencyKey, retry = true, ...fields }) {
66
+ const body = { resource_type: resourceType, ...RareeaiSubmodule._body("provide", fields) };
67
+ const cap = capacityTotal ?? capacity;
68
+ if (cap != null) body.capacity_total = cap;
41
69
  return this._t.request(this._base, "POST", `${this._p}/provide`, { body, idempotencyKey, retry });
42
70
  }
43
71
  // ENFORCED-WHEN-PRESENT / BEST-EFFORT-keyless (routes.py:1282 guard; SDK dispatch
44
72
  // always auto-gens a key → SDK callers effectively enforced; keyless gap raw-HTTP-only).
45
73
  createRequest({ resourceType, idempotencyKey, retry = true, ...fields }) {
46
74
  return this._t.request(this._base, "POST", `${this._p}/request`,
47
- { body: { resource_type: resourceType, ...fields }, idempotencyKey, retry });
75
+ { body: { resource_type: resourceType, ...RareeaiSubmodule._body("request", fields) }, idempotencyKey, retry });
48
76
  }
49
77
  // 0.3.3: delivery enters the post-delivery hold (no inline release); the
50
78
  // buyer accepts via accept(), disputes, or the hold expires. resultHash /
@@ -55,7 +83,7 @@ export class RareeaiSubmodule {
55
83
  if (resultHash) params.result_hash = resultHash;
56
84
  if (resultUri) params.result_uri = resultUri;
57
85
  return this._t.request(this._base, "POST", `${this._p}/deliver/{match_id}`,
58
- { pathParams: { match_id: matchId }, body: fields,
86
+ { pathParams: { match_id: matchId }, body: RareeaiSubmodule._body("deliver", fields),
59
87
  params: Object.keys(params).length ? params : undefined, idempotencyKey, retry });
60
88
  }
61
89
  // 0.3.3: the PRIMARY settlement path — buyer-only immediate release of a
@@ -66,25 +94,25 @@ export class RareeaiSubmodule {
66
94
  }
67
95
  resolve(matchId, { idempotencyKey, retry = true, ...fields } = {}) {
68
96
  return this._t.request(this._base, "POST", `${this._p}/match/{match_id}/resolve`,
69
- { pathParams: { match_id: matchId }, body: fields, idempotencyKey, retry });
97
+ { pathParams: { match_id: matchId }, body: RareeaiSubmodule._body("resolve", fields), idempotencyKey, retry });
70
98
  }
71
99
 
72
100
  // FSM transitions — NOT SUPPORTED (auto-retry OFF)
73
101
  approve(matchId, fields = {}) {
74
102
  return this._t.request(this._base, "POST", `${this._p}/match/{match_id}/approve`,
75
- { pathParams: { match_id: matchId }, body: fields });
103
+ { pathParams: { match_id: matchId }, body: RareeaiSubmodule._body("approve", fields) });
76
104
  }
77
105
  reject(matchId, fields = {}) {
78
106
  return this._t.request(this._base, "POST", `${this._p}/match/{match_id}/reject`,
79
- { pathParams: { match_id: matchId }, body: fields });
107
+ { pathParams: { match_id: matchId }, body: RareeaiSubmodule._body("reject", fields) });
80
108
  }
81
109
  dispute(matchId, fields = {}) {
82
110
  return this._t.request(this._base, "POST", `${this._p}/match/{match_id}/dispute`,
83
- { pathParams: { match_id: matchId }, body: fields });
111
+ { pathParams: { match_id: matchId }, body: RareeaiSubmodule._body("dispute", fields) });
84
112
  }
85
113
  extendDispute(matchId, fields = {}) {
86
114
  return this._t.request(this._base, "POST", `${this._p}/match/{match_id}/extend-dispute`,
87
- { pathParams: { match_id: matchId }, body: fields });
115
+ { pathParams: { match_id: matchId }, body: RareeaiSubmodule._body("extend_dispute", fields) });
88
116
  }
89
117
 
90
118
  // reads
@@ -134,6 +162,10 @@ export class RareeaiSubmodule {
134
162
  // 50-5,000 joules total, split across the match's oracles — deducted from the trade at
135
163
  // settlement. Assess within the 48-hour deadline. NOT auto-retried (no verified server
136
164
  // idempotency claim on this path).
165
+ // 409 = LATE: the match already advanced (oracle_status verified/failed/disputed, or it left
166
+ // escrowed/delivered) — your verdict is moot; do not retry, read the match. Consensus is a MAJORITY
167
+ // of assigned oracles (floor 2), not all-must-report: once a majority lands the trade settles and
168
+ // remaining assignments EXPIRE (a late assess then 409s).
137
169
  oracleAssess(matchId, { verdict, qualityScore, notes = "", executionTrace, ...fields }) {
138
170
  const body = { verdict, quality_score: qualityScore, notes, ...fields };
139
171
  if (executionTrace !== undefined) body.execution_trace = executionTrace;