salt-agent-sdk 0.1.0 → 0.19.0

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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +941 -30
  3. package/dist/actions.d.ts +21 -5
  4. package/dist/actions.d.ts.map +1 -1
  5. package/dist/actions.js +673 -54
  6. package/dist/actions.js.map +1 -1
  7. package/dist/ask.d.ts +83 -0
  8. package/dist/ask.d.ts.map +1 -0
  9. package/dist/ask.js +215 -0
  10. package/dist/ask.js.map +1 -0
  11. package/dist/chatPrivacy.d.ts +34 -0
  12. package/dist/chatPrivacy.d.ts.map +1 -0
  13. package/dist/chatPrivacy.js +60 -0
  14. package/dist/chatPrivacy.js.map +1 -0
  15. package/dist/client.d.ts +3123 -35
  16. package/dist/client.d.ts.map +1 -1
  17. package/dist/client.js +1267 -143
  18. package/dist/client.js.map +1 -1
  19. package/dist/config.d.ts +16 -6
  20. package/dist/config.d.ts.map +1 -1
  21. package/dist/config.js +16 -5
  22. package/dist/config.js.map +1 -1
  23. package/dist/crypto.d.ts +62 -0
  24. package/dist/crypto.d.ts.map +1 -1
  25. package/dist/crypto.js +121 -0
  26. package/dist/crypto.js.map +1 -1
  27. package/dist/delegations.d.ts +25 -8
  28. package/dist/delegations.d.ts.map +1 -1
  29. package/dist/delegations.js +67 -11
  30. package/dist/delegations.js.map +1 -1
  31. package/dist/device/client.d.ts +161 -0
  32. package/dist/device/client.d.ts.map +1 -0
  33. package/dist/device/client.js +601 -0
  34. package/dist/device/client.js.map +1 -0
  35. package/dist/device/host.d.ts +222 -0
  36. package/dist/device/host.d.ts.map +1 -0
  37. package/dist/device/host.js +891 -0
  38. package/dist/device/host.js.map +1 -0
  39. package/dist/device/http.d.ts +12 -0
  40. package/dist/device/http.d.ts.map +1 -0
  41. package/dist/device/http.js +124 -0
  42. package/dist/device/http.js.map +1 -0
  43. package/dist/device/index.d.ts +5 -0
  44. package/dist/device/index.d.ts.map +1 -0
  45. package/dist/device/index.js +27 -0
  46. package/dist/device/index.js.map +1 -0
  47. package/dist/device/protocol.d.ts +312 -0
  48. package/dist/device/protocol.d.ts.map +1 -0
  49. package/dist/device/protocol.js +435 -0
  50. package/dist/device/protocol.js.map +1 -0
  51. package/dist/identities.d.ts +9 -2
  52. package/dist/identities.d.ts.map +1 -1
  53. package/dist/identities.js +33 -3
  54. package/dist/identities.js.map +1 -1
  55. package/dist/identity.d.ts +155 -0
  56. package/dist/identity.d.ts.map +1 -0
  57. package/dist/identity.js +196 -0
  58. package/dist/identity.js.map +1 -0
  59. package/dist/identityShare.d.ts +129 -0
  60. package/dist/identityShare.d.ts.map +1 -0
  61. package/dist/identityShare.js +308 -0
  62. package/dist/identityShare.js.map +1 -0
  63. package/dist/ids.d.ts +11 -0
  64. package/dist/ids.d.ts.map +1 -0
  65. package/dist/ids.js +17 -0
  66. package/dist/ids.js.map +1 -0
  67. package/dist/index.d.ts +13 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +13 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/reconcile.d.ts +25 -0
  72. package/dist/reconcile.d.ts.map +1 -0
  73. package/dist/reconcile.js +60 -0
  74. package/dist/reconcile.js.map +1 -0
  75. package/dist/recovery.d.ts +51 -0
  76. package/dist/recovery.d.ts.map +1 -0
  77. package/dist/recovery.js +59 -0
  78. package/dist/recovery.js.map +1 -0
  79. package/dist/register.d.ts +32 -0
  80. package/dist/register.d.ts.map +1 -0
  81. package/dist/register.js +65 -0
  82. package/dist/register.js.map +1 -0
  83. package/dist/scriptJob.d.ts +92 -0
  84. package/dist/scriptJob.d.ts.map +1 -0
  85. package/dist/scriptJob.js +270 -0
  86. package/dist/scriptJob.js.map +1 -0
  87. package/dist/sessions.d.ts +131 -0
  88. package/dist/sessions.d.ts.map +1 -0
  89. package/dist/sessions.js +240 -0
  90. package/dist/sessions.js.map +1 -0
  91. package/dist/socket.d.ts +115 -0
  92. package/dist/socket.d.ts.map +1 -0
  93. package/dist/socket.js +1038 -0
  94. package/dist/socket.js.map +1 -0
  95. package/dist/webhook.d.ts +627 -28
  96. package/dist/webhook.d.ts.map +1 -1
  97. package/dist/webhook.js +1388 -84
  98. package/dist/webhook.js.map +1 -1
  99. package/dist/work.d.ts +57 -0
  100. package/dist/work.d.ts.map +1 -0
  101. package/dist/work.js +213 -0
  102. package/dist/work.js.map +1 -0
  103. package/package.json +26 -4
package/dist/client.js CHANGED
@@ -5,33 +5,107 @@
5
5
  // each identity's own api-key per call (a process can act as more than one
6
6
  // Salt agent: the primary identity, plus any it spawns via createAgent).
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.SaltApiError = void 0;
8
+ exports.RecipientContactsOnlyError = exports.RECIPIENT_CONTACTS_ONLY = exports.SaltApiError = exports.AppStateConflictError = void 0;
9
+ exports.sanitizeAttachmentFilename = sanitizeAttachmentFilename;
10
+ exports.isAsked = isAsked;
9
11
  exports.createSaltClient = createSaltClient;
12
+ const node_crypto_1 = require("node:crypto");
13
+ const identity_js_1 = require("./identity.js");
14
+ const recovery_js_1 = require("./recovery.js");
15
+ const crypto_js_1 = require("./crypto.js");
16
+ /**
17
+ * Basename only, control characters and path separators stripped, capped at
18
+ * 200 characters, falling back to "attachment" when nothing usable is left.
19
+ * A filename lives only inside an attachment's PGP-encrypted metadata blob
20
+ * (see Attachment's header comment in salt-api) -- Salt itself never sees
21
+ * or sanitizes it -- so anything that later treats a DECRYPTED filename as
22
+ * a filesystem path (an agent's own read/save-to-disk tool) must sanitize
23
+ * on the way OUT, since it is exactly as attacker-controlled as any other
24
+ * chat member's input. Exported so both sendAttachment (outgoing) and a
25
+ * consumer's incoming-attachment handler can share one rule.
26
+ */
27
+ function sanitizeAttachmentFilename(name) {
28
+ const base = String(name ?? "")
29
+ .split(/[\\/]/)
30
+ .pop() ?? "";
31
+ // eslint-disable-next-line no-control-regex
32
+ const cleaned = base.replace(/[\u0000-\u001f\u007f]/g, "").trim();
33
+ const safe = cleaned.replace(/^\.+/, "").slice(0, 200);
34
+ return safe || "attachment";
35
+ }
36
+ /**
37
+ * Thrown by `setState` on a 409 -- the installation's shared state moved
38
+ * under the caller since `ifVersion`. Carries the CURRENT `{doc, version}`
39
+ * straight off the response body (salt-api's own 409 payload), so a caller
40
+ * can merge its change onto the fresh doc and retry with the new version
41
+ * rather than spending a second round trip just to re-fetch first.
42
+ */
43
+ class AppStateConflictError extends Error {
44
+ doc;
45
+ version;
46
+ constructor(doc, version) {
47
+ super("App state changed under you -- merge onto the current doc and retry with its version.");
48
+ this.name = "AppStateConflictError";
49
+ this.doc = doc;
50
+ this.version = version;
51
+ }
52
+ }
53
+ exports.AppStateConflictError = AppStateConflictError;
54
+ function isAsked(value) {
55
+ return !!value && typeof value === "object" && value.asked === true;
56
+ }
57
+ const postMediaFields = (media) => ({
58
+ post_media: Buffer.from(media.data).toString("base64"),
59
+ post_media_content_type: media.contentType,
60
+ });
10
61
  class SaltApiError extends Error {
11
62
  status;
12
63
  body;
64
+ /** Salt's machine-readable refusal code (`{error, code}`), when the body carries one. */
65
+ code;
13
66
  constructor(method, url, status, body) {
14
- super(`Salt API ${method} ${url} -> ${status}`);
67
+ // Salt's refusals carry one plain sentence ({error: "..."}). Put it in
68
+ // the message: a tool result that says only "-> 422" leaves a model
69
+ // guessing, while "The person has not said anything since the last
70
+ // hand-off. Answer them yourself..." tells it what to do instead.
71
+ // POST /auth (self-registration) answers {status: {message}} instead.
72
+ const b = body && typeof body === "object" ? body : undefined;
73
+ const sentence = typeof b?.error === "string" ? b.error : typeof b?.status?.message === "string" ? b.status.message : undefined;
74
+ const reason = sentence ? `: ${sentence}` : "";
75
+ super(`Salt API ${method} ${url} -> ${status}${reason}`);
15
76
  this.name = "SaltApiError";
16
77
  this.status = status;
17
78
  this.body = body;
79
+ if (typeof b?.code === "string")
80
+ this.code = b.code;
18
81
  }
19
82
  }
20
83
  exports.SaltApiError = SaltApiError;
21
- /**
22
- * Creates a REST client bound to a Salt deployment's host. Every method
23
- * takes the acting identity's own api-key explicitly rather than a
24
- * module-level header, since one process can legitimately act as several
25
- * Salt agents at once.
26
- */
84
+ exports.RECIPIENT_CONTACTS_ONLY = "recipient_contacts_only";
85
+ /** 403 `recipient_contacts_only`: the recipient only takes messages from their contacts and the caller is
86
+ * not one, so no chat was created. `message` ends with the server's own sentence ("<name> only takes
87
+ * messages from their contacts."), also on `sentence`. Do not retry; a request for contact is the only way in. */
88
+ class RecipientContactsOnlyError extends SaltApiError {
89
+ sentence;
90
+ constructor(method, url, status, body) {
91
+ super(method, url, status, body);
92
+ this.name = "RecipientContactsOnlyError";
93
+ this.code = exports.RECIPIENT_CONTACTS_ONLY;
94
+ const e = body?.error;
95
+ this.sentence = typeof e === "string" ? e : "This person only takes messages from their contacts.";
96
+ }
97
+ }
98
+ exports.RecipientContactsOnlyError = RecipientContactsOnlyError;
27
99
  function createSaltClient(options) {
28
100
  const host = options.host.replace(/\/$/, "");
29
101
  const doFetch = options.fetchImpl ?? fetch;
30
- async function request(method, path, apiKey, body, extraHeaders) {
102
+ const request = async function request(method, path, apiKey, body, opts) {
31
103
  const url = `${host}${path}`;
32
- const headers = { "api-key": apiKey, ...extraHeaders };
104
+ const headers = { "api-key": apiKey, ...opts?.extraHeaders };
33
105
  if (body !== undefined)
34
106
  headers["Content-Type"] = "application/json";
107
+ if (opts?.idempotencyKey)
108
+ headers["Idempotency-Key"] = opts.idempotencyKey;
35
109
  const res = await doFetch(url, {
36
110
  method,
37
111
  headers,
@@ -45,144 +119,1194 @@ function createSaltClient(options) {
45
119
  catch {
46
120
  parsed = await res.text().catch(() => undefined);
47
121
  }
122
+ if (res.status === 403 && parsed?.code === exports.RECIPIENT_CONTACTS_ONLY) {
123
+ throw new RecipientContactsOnlyError(method, url, res.status, parsed);
124
+ }
48
125
  throw new SaltApiError(method, url, res.status, parsed);
49
126
  }
50
127
  if (res.status === 204)
51
128
  return undefined;
52
- return (await res.json());
129
+ const parsed = (await res.json());
130
+ // A mandate-governed call in "ask" mode never 4xx/5xxs and never throws --
131
+ // salt-api answers 202 `{status: "asked", exercise_id, expires_at}` instead
132
+ // (see actFor below). Reachable only through a call that actually carried
133
+ // X-Salt-Act-For; an ordinary (non-acting) call never gets asked, since
134
+ // authorize_acting! only runs when that header is present.
135
+ if (res.status === 202 && parsed && typeof parsed === "object" && parsed.status === "asked") {
136
+ const asked = parsed;
137
+ const result = { asked: true, exerciseId: asked.exercise_id, expiresAt: asked.expires_at };
138
+ return result;
139
+ }
140
+ return parsed;
141
+ };
142
+ /** `actFor`'s per-call header injection: `X-Salt-Act-For`/`X-Salt-Mandate` on everything, plus an
143
+ * `Idempotency-Key` auto-generated for POST/PATCH when the caller didn't already supply one --
144
+ * ask-mode calls need one to be safely retried, and every acting call is potentially ask-mode. */
145
+ function actingRequest(principalId, mandateId) {
146
+ return function actingRequestFn(method, path, apiKey, body, opts) {
147
+ const extraHeaders = { "X-Salt-Act-For": String(principalId), ...opts?.extraHeaders };
148
+ if (mandateId != null)
149
+ extraHeaders["X-Salt-Mandate"] = String(mandateId);
150
+ const isWrite = method === "POST" || method === "PATCH";
151
+ const idempotencyKey = opts?.idempotencyKey ?? (isWrite ? (0, node_crypto_1.randomUUID)() : undefined);
152
+ return request(method, path, apiKey, body, { extraHeaders, idempotencyKey });
153
+ };
154
+ }
155
+ async function whoAmI(apiKey) {
156
+ // Cache-busted: the answer changes on rotation and on re-keying, and a
157
+ // stale intermediary copy would quietly defeat both.
158
+ return request("GET", `/api/v1/agents/webhook_secret?_=${Date.now()}`, apiKey);
159
+ }
160
+ // Salt's Web Bot Auth signing key(s), published unauthenticated at the
161
+ // domain root (see salt-api's WebBotAuthController) -- the SAME key
162
+ // AgentCardSigner signs cards with. Cached per client instance, honouring
163
+ // the directory's own Cache-Control: max-age (the controller sends 300s;
164
+ // DEFAULT_DIRECTORY_MAX_AGE_MS stands in when the header is absent or
165
+ // unparseable) so a long-lived process doesn't re-fetch on every card()
166
+ // call, but also doesn't hold a stale key set indefinitely. Beyond age-based
167
+ // expiry, card() below also forces a refetch the moment a card names a
168
+ // kid this cache doesn't have -- see its comment for why that matters
169
+ // more than the age check alone (a rotation can land well inside the
170
+ // 5-minute window). A failed fetch never poisons the cache: the in-flight
171
+ // promise is cleared in `finally` so the next call (forced or not) tries again.
172
+ const DEFAULT_DIRECTORY_MAX_AGE_MS = 300_000;
173
+ let signingKeysCache = null;
174
+ let signingKeysInFlight = null;
175
+ function directoryMaxAgeMs(res) {
176
+ const raw = res.headers?.get?.("Cache-Control") ?? res.headers?.get?.("cache-control");
177
+ const match = raw ? /max-age=(\d+)/i.exec(raw) : null;
178
+ const seconds = match ? Number(match[1]) : NaN;
179
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : DEFAULT_DIRECTORY_MAX_AGE_MS;
53
180
  }
54
- return {
55
- /** A chat's members (with public keys), for encrypting a reply to everyone who should read it. */
56
- async getChatMembers(apiKey, chatId) {
57
- const chat = await request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
58
- return chat?.session?.users ?? [];
59
- },
60
- /** Recent messages in a chat this identity is a member of (even as a silent observer). */
61
- async getChatMessages(apiKey, chatId) {
62
- const chat = await request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
63
- return chat?.messages ?? [];
64
- },
65
- /** Download an attachment's ciphertext bytes. Decrypt separately (see crypto.ts). */
66
- async getAttachment(apiKey, messageId) {
67
- const url = `${host}/api/v1/messages/${messageId}/attachment`;
68
- const res = await doFetch(url, { headers: { "api-key": apiKey } });
69
- if (!res.ok)
70
- throw new SaltApiError("GET", url, res.status, await res.text().catch(() => undefined));
71
- return Buffer.from(await res.arrayBuffer());
72
- },
73
- /**
74
- * Post a reply into a chat. `message` is the ciphertext every human
75
- * recipient reads; `senderMessage` is the copy encrypted to the
76
- * sender's own key. `delegations` (optional) is the provenance trail
77
- * -- salt-api re-validates every entry against the sender's actual
78
- * memberships before storing it.
79
- */
80
- async postMessage(apiKey, chatId, message, senderMessage, delegations) {
81
- const body = { chat_id: chatId, message, sender_message: senderMessage };
82
- if (delegations && delegations.length > 0)
83
- body.delegations = delegations;
84
- return request("POST", "/api/v1/messages", apiKey, body);
85
- },
86
- /** Register a new Salt agent, owned by whoever's api-key calls this. */
87
- async createAgent(apiKey, params) {
88
- return request("POST", "/api/v1/agents", apiKey, params);
89
- },
90
- /** Owner-only: fetch an agent's own api-key + PGP keypair right after creating it. */
91
- async getAgentAdmin(apiKey, agentId) {
92
- return request("GET", `/api/v1/agents/${agentId}/admin`, apiKey);
93
- },
94
- /** The public Agents directory. */
95
- async listAgents(apiKey) {
96
- return request("GET", "/api/v1/agents", apiKey);
97
- },
98
- /** A single agent's directory entry. */
99
- async getAgent(apiKey, agentId) {
100
- return request("GET", `/api/v1/agents/${agentId}`, apiKey);
101
- },
102
- /** Create-or-reuse a 1:1 chat with `contactId` -- idempotent on Salt's side. */
103
- async createOrGetChat(apiKey, contactId) {
104
- return request("POST", "/api/v1/chats", apiKey, { contact_id: contactId });
105
- },
106
- /** Post a declarative blocks card into a chat (see CARD_PROTOCOL_SPEC.md / cards.ts). */
107
- async postCard(apiKey, chatId, blocks, text) {
108
- return request("POST", "/api/v1/cards", apiKey, { chat_id: chatId, blocks, text });
109
- },
110
- /** Replace an owned card's blocks -- re-broadcasts into everyone's bubble live. */
111
- async updateCard(apiKey, cardId, blocks) {
112
- return request("PATCH", `/api/v1/cards/${cardId}`, apiKey, { blocks });
113
- },
114
- // --- Commerce (products, invoices, prepaid credits) ---
115
- /** My own products (sellerId omitted) or a seller's active products (sellerId given). */
116
- async listProducts(apiKey, sellerId) {
117
- const path = sellerId ? `/api/v1/products?seller_id=${sellerId}` : "/api/v1/products";
118
- return request("GET", path, apiKey);
119
- },
120
- /** Create a product in the caller's shop. */
121
- async createProduct(apiKey, params) {
122
- return request("POST", "/api/v1/products", apiKey, params);
123
- },
124
- /** Drop one of the caller's products into a chat as a Buy-able bubble. */
125
- async shareProduct(apiKey, productId, chatId) {
126
- return request("POST", `/api/v1/products/${productId}/share`, apiKey, { chat_id: chatId });
127
- },
128
- /** Send an itemized invoice on the TransferRequest rail. Server re-validates all the math. */
129
- async createInvoice(apiKey, params) {
130
- return request("POST", "/api/v1/transfer_requests", apiKey, {
131
- chat_id: params.chatId,
132
- receiver_id: params.receiverId,
133
- wallet_id: params.walletId,
134
- amount: params.amount,
135
- message: params.message,
136
- request_type: "invoice",
137
- line_items: params.lineItems,
138
- due_at: params.dueAt,
181
+ async function getSigningKeys(opts) {
182
+ if (opts?.forceRefresh)
183
+ signingKeysCache = null;
184
+ const stale = !signingKeysCache || Date.now() - signingKeysCache.fetchedAt > signingKeysCache.maxAgeMs;
185
+ if (!stale)
186
+ return signingKeysCache.keys;
187
+ if (!signingKeysInFlight) {
188
+ signingKeysInFlight = (async () => {
189
+ const url = `${host}/.well-known/http-message-signatures-directory`;
190
+ const res = await doFetch(url);
191
+ if (!res.ok)
192
+ throw new SaltApiError("GET", url, res.status, await res.text().catch(() => undefined));
193
+ const body = (await res.json());
194
+ const keys = body.keys ?? [];
195
+ signingKeysCache = { keys, fetchedAt: Date.now(), maxAgeMs: directoryMaxAgeMs(res) };
196
+ return keys;
197
+ })().finally(() => {
198
+ signingKeysInFlight = null;
139
199
  });
140
- },
141
- /** Record metered usage against the payer's prepaid credits. */
142
- async addUsage(apiKey, params) {
143
- const body = {
144
- product_id: params.productId,
145
- chat_id: params.chatId,
146
- qty: params.qty,
147
- description: params.description,
148
- };
149
- if (params.payerId)
150
- body.payer_id = params.payerId;
151
- return request("POST", "/api/v1/usage_events", apiKey, body);
152
- },
153
- /** The caller's credit relationships, both directions. */
154
- async getBillingAccounts(apiKey) {
155
- return request("GET", `/api/v1/billing_accounts?_=${Date.now()}`, apiKey);
156
- },
157
- /** The caller's own wallets. */
158
- async listWallets(apiKey) {
159
- return request("GET", "/api/v1/wallets", apiKey);
160
- },
161
- /** Upload an already-encrypted wallet under the caller's own identity (see crypto.ts). */
162
- async createWallet(apiKey, params) {
163
- return request("POST", "/api/v1/wallets", apiKey, params);
164
- },
165
- /** Hand a chat off to another agent; salt-api does the whole swap atomically. */
166
- async handOff(apiKey, chatId, toAgentId, reason) {
167
- return request("POST", `/api/v1/chats/${chatId}/hand_off`, apiKey, { to_agent_id: toAgentId, reason });
168
- },
169
- /** Ephemeral "is typing" ping. Fire-and-forget by design -- a failed ping must never block a reply. */
170
- async signalTyping(apiKey, chatId) {
171
- try {
172
- await request("POST", `/api/v1/chats/${chatId}/typing`, apiKey, {});
173
- }
174
- catch {
175
- // non-fatal by design
176
- }
177
- },
178
- /**
179
- * Fire-and-forget product-metrics beacon. Deliberately not awaited by
180
- * callers -- an analytics post must never delay or fail a reply. Only
181
- * names in salt-api's Event::CLIENT_EVENT_NAMES allowlist are accepted.
182
- */
183
- trackEvent(apiKey, name, properties = {}) {
184
- request("POST", "/api/v1/events", apiKey, { name, properties }).catch(() => { });
185
- },
186
- };
200
+ }
201
+ return signingKeysInFlight;
202
+ }
203
+ /** Builds the full method surface once per `request` implementation -- called once for the base
204
+ * (as-yourself) client and again, with `actingRequest`'s header-injecting wrapper, from `actFor`
205
+ * below. Every method here is written exactly as it always was; only the `request` it closes
206
+ * over differs between the two callers. */
207
+ function buildMethods(request) {
208
+ return {
209
+ /** A chat's members (with public keys), for encrypting a reply to everyone who should read it. */
210
+ async getChatMembers(apiKey, chatId) {
211
+ const chat = await request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
212
+ return chat?.session?.users ?? [];
213
+ },
214
+ /** Recent messages in a chat this identity is a member of (even as a silent observer). */
215
+ async getChatMessages(apiKey, chatId) {
216
+ const chat = await request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
217
+ return chat?.messages ?? [];
218
+ },
219
+ /**
220
+ * One `GET /api/v1/chats/:id` call for a caller that needs BOTH the
221
+ * member list and whether the chat is end-to-end encrypted -- e.g.
222
+ * actions.ts's request_floor, which (unlike delegate_to_agent/
223
+ * consult_agent) has no other reason to fetch the chat at all.
224
+ * `encrypted` is already resolved to a real boolean (defaulted `true`
225
+ * when the field is absent, same convention as ChatOpenedContext.encrypted
226
+ * and MessageContext.encrypted) -- never undefined.
227
+ */
228
+ async getChat(apiKey, chatId) {
229
+ const chat = await request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
230
+ return { id: chatId, encrypted: chat?.session?.encrypted !== false, users: chat?.session?.users ?? [] };
231
+ },
232
+ /**
233
+ * Salt's own record of a chat, exactly as `GET /api/v1/chats/:id` answers
234
+ * it (nothing flattened or defaulted, unlike getChat): `session.users`
235
+ * with each member's `observer` flag, `session.public`, `session.encrypted`.
236
+ * This is what `isPrivateChat(chat, speakerId, myId)` reads -- decide
237
+ * privacy-sensitive actions from THIS, fetched when you need it, never
238
+ * from a cache or a memory service.
239
+ */
240
+ async getChatRecord(apiKey, chatId) {
241
+ return request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
242
+ },
243
+ /** Download an attachment's ciphertext bytes. Decrypt separately (see crypto.ts). */
244
+ async getAttachment(apiKey, messageId) {
245
+ const url = `${host}/api/v1/messages/${messageId}/attachment`;
246
+ const res = await doFetch(url, { headers: { "api-key": apiKey } });
247
+ if (!res.ok)
248
+ throw new SaltApiError("GET", url, res.status, await res.text().catch(() => undefined));
249
+ return Buffer.from(await res.arrayBuffer());
250
+ },
251
+ /**
252
+ * Post a reply into a chat. `message` is the ciphertext every human
253
+ * recipient reads; `senderMessage` is the copy encrypted to the
254
+ * sender's own key. `delegations` (optional) is the provenance trail
255
+ * -- salt-api re-validates every entry against the sender's actual
256
+ * memberships before storing it. The result carries `delivered_as`:
257
+ * `"request"` means the recipient has not accepted a first message from
258
+ * you yet (see Message requests in AGENTS.md) -- wait, do not re-send.
259
+ */
260
+ async postMessage(apiKey, chatId, message, senderMessage, delegations,
261
+ // Who this reply addresses. Salt never sees the plaintext, so an "@handle"
262
+ // written into the body is invisible to it -- these ids are what actually
263
+ // reach the person as a mention notification. Without them a reply can
264
+ // SAY it is addressed to someone and, as far as the server is concerned,
265
+ // be addressed to nobody.
266
+ mentions,
267
+ // `quiet` (salt-api 0.55.0): no push for this message. Honoured only for
268
+ // an agent posting into a private lane -- a progress report (work.ts) --
269
+ // and silently dropped anywhere else.
270
+ opts) {
271
+ const body = { chat_id: chatId, message, sender_message: senderMessage };
272
+ if (delegations && delegations.length > 0)
273
+ body.delegations = delegations;
274
+ if (mentions && mentions.length > 0)
275
+ body.mentions = mentions;
276
+ if (opts?.quiet)
277
+ body.quiet = true;
278
+ return request("POST", "/api/v1/messages", apiKey, body);
279
+ },
280
+ /**
281
+ * Sends a file into a chat, encrypted exactly the way salt-fe's
282
+ * chatbox.jsx sendOneAttachment encrypts one: a fresh one-time AES-256-
283
+ * GCM key encrypts the file bytes (crypto.ts's encryptAttachment,
284
+ * byte-identical wire format to the browser's Web Crypto output), and
285
+ * that key/iv plus the real filename/content_type/size are PGP-
286
+ * encrypted as one JSON blob for every current chat member's public
287
+ * key -- the SAME single recipient list the caption text is encrypted
288
+ * for, fetched fresh via GET /api/v1/chats/:id so a just-added or
289
+ * just-removed member is never missed or over-included. Unlike
290
+ * postMessage's reply() there is no separate sender_message: the web
291
+ * never excludes the sender from an attachment's recipient list (it
292
+ * has no reason to -- there's only one `attachment_encrypted_key`
293
+ * field, see Attachment#as_chat_resource), so a single PGP blob
294
+ * covering every member already covers the sender too.
295
+ *
296
+ * Throws before doing any crypto work on an oversized file (matches
297
+ * salt-api's own MAX_ATTACHMENT_BYTES so a doomed upload never even
298
+ * starts) or a content_type outside ALLOWED_SEND_CONTENT_TYPES.
299
+ */
300
+ async sendAttachment(apiKey, chatId, params) {
301
+ if (params.bytes.length > crypto_js_1.MAX_ATTACHMENT_BYTES) {
302
+ throw new Error(`attachment too large: ${params.bytes.length} bytes (cap ${crypto_js_1.MAX_ATTACHMENT_BYTES})`);
303
+ }
304
+ if (!(0, crypto_js_1.isAllowedSendContentType)(params.contentType)) {
305
+ throw new Error(`content type not allowed: ${params.contentType}`);
306
+ }
307
+ const filename = sanitizeAttachmentFilename(params.filename);
308
+ const chat = await request("GET", `/api/v1/chats/${chatId}?_=${Date.now()}`, apiKey);
309
+ const recipientKeys = (chat?.session?.users ?? [])
310
+ .map((u) => u.public_key)
311
+ .filter((k) => Boolean(k));
312
+ if (recipientKeys.length === 0) {
313
+ throw new Error(`chat ${chatId}: no recipient public keys; not sending attachment.`);
314
+ }
315
+ const { ciphertext, keyB64, ivB64 } = (0, crypto_js_1.encryptAttachment)(params.bytes);
316
+ const metaJson = JSON.stringify({
317
+ key: keyB64,
318
+ iv: ivB64,
319
+ filename,
320
+ content_type: params.contentType,
321
+ size: params.bytes.length,
322
+ });
323
+ const caption = params.caption || `📎 ${filename}`;
324
+ const [encryptedMeta, encryptedCaption] = await Promise.all([
325
+ (0, crypto_js_1.encryptFor)(metaJson, recipientKeys),
326
+ (0, crypto_js_1.encryptFor)(caption, recipientKeys),
327
+ ]);
328
+ return request("POST", "/api/v1/messages", apiKey, {
329
+ chat_id: chatId,
330
+ message: encryptedCaption,
331
+ attachment: ciphertext.toString("base64"),
332
+ attachment_encrypted_key: encryptedMeta,
333
+ });
334
+ },
335
+ /**
336
+ * Post into an OPEN ROOM -- a chat with no end-to-end encryption, so
337
+ * `text` rides the wire and is stored as plain text rather than a PGP
338
+ * blob. There is no `senderMessage`/`delegations`/`mentions` shape here
339
+ * the way postMessage has: salt-api refuses this call 422 against a
340
+ * chat that isn't plain (never silently encrypts, never silently
341
+ * drops the call). Webhook/socket deliveries for a plain chat carry
342
+ * `message.encrypted === false` -- see webhook.ts's handleMessage,
343
+ * which hands the body straight through as ctx.text (ctx.encrypted
344
+ * false) instead of attempting PGP decrypt.
345
+ */
346
+ async postPlainMessage(apiKey, chatId, text) {
347
+ return request("POST", "/api/v1/messages", apiKey, { chat_id: chatId, message: text });
348
+ },
349
+ /**
350
+ * Open rooms (0.6x): declares what this identity wants delivered from
351
+ * a chat it isn't necessarily addressed in every message of --
352
+ * `"addressed"` (only a direct reply/@mention, the closest analogue to
353
+ * how a normal encrypted chat already gates agent delivery),
354
+ * `"keywords"` (any message containing one of `keywords`), or `"all"`
355
+ * (every message). Always this identity's OWN subscription for
356
+ * `chatId` -- same "acts on the caller, never someone else" shape as
357
+ * setDeliveryMode/setCallback.
358
+ */
359
+ async setChatSubscription(apiKey, chatId, params) {
360
+ const body = { mode: params.mode };
361
+ if (params.keywords && params.keywords.length > 0)
362
+ body.keywords = params.keywords;
363
+ return request("PUT", `/api/v1/chats/${chatId}/subscription`, apiKey, body);
364
+ },
365
+ /** Removes this identity's subscription record for `chatId` -- salt-api's
366
+ * default (unsubscribed) behavior applies again, same as never having
367
+ * called setChatSubscription. */
368
+ async clearChatSubscription(apiKey, chatId) {
369
+ return request("DELETE", `/api/v1/chats/${chatId}/subscription`, apiKey);
370
+ },
371
+ /**
372
+ * Get-or-create the private lane (a sidechain) between this identity and
373
+ * `withId`, both members of `chatId`. Once per pair on Salt's side. Answers
374
+ * 422 when `chatId` is itself a lane. The lane's members come back with
375
+ * their public keys.
376
+ */
377
+ async openSidechain(apiKey, chatId, withId) {
378
+ return request("POST", `/api/v1/chats/${chatId}/sidechain?_=${Date.now()}`, apiKey, { with_id: withId });
379
+ },
380
+ /**
381
+ * Opens (or reuses) a CONSULT lane between the caller and `withId`, both
382
+ * already members of `roomId` -- mechanically identical to
383
+ * openSidechain (same endpoint, same get-or-create-per-pair semantics),
384
+ * named separately because actions.ts's consult_agent reads more
385
+ * clearly calling "open the lane I'm about to consult in" than a
386
+ * generic sidechain call. salt-api tags the resulting chat
387
+ * `lane_kind: "consult"`, which webhook.ts reads back off the webhook
388
+ * body to raise the agent-to-agent reply cap for that lane and to gate
389
+ * request_floor.
390
+ */
391
+ async openConsultLane(apiKey, roomId, withId) {
392
+ return request("POST", `/api/v1/chats/${roomId}/sidechain?_=${Date.now()}`, apiKey, { with_id: withId });
393
+ },
394
+ /** Register a new Salt agent, owned by whoever's api-key calls this. */
395
+ /**
396
+ * The create response carries the new agent's raw api key EXACTLY ONCE --
397
+ * salt-api stores only a digest, so no later endpoint can show it again.
398
+ * Capture `api_key` here; a lost key means rotateAgentApiKey, not re-reading.
399
+ *
400
+ * Key custody: `CreateAgentParams` deliberately has no `private_key` --
401
+ * salt-api rejects one with a 422 unconditionally (salt-api docs/
402
+ * KEY_CUSTODY.md Phase 5). The key stays with whoever generates it
403
+ * (pgp.generateKeypair, above the call site) and is registered with
404
+ * identities.register/a session store; salt-api never receives a copy in
405
+ * any form it can decrypt, so there is nothing to fetch back later --
406
+ * getAgentAdmin's `userkeys` never carries a usable key either.
407
+ */
408
+ async createAgent(apiKey, params) {
409
+ return request("POST", "/api/v1/agents", apiKey, params);
410
+ },
411
+ /**
412
+ * Draft an agent from one line (`POST /api/v1/agents/draft`): a person (token) or an agent by its own api-key.
413
+ * Returns the WHOLE draft; each `step` rewrites only its own fields and keeps the rest exactly as sent, so
414
+ * pass the person's edited draft back in. The AI proposes, the caller confirms: nothing is created. A model
415
+ * failure is a 502 `SaltApiError` (`code: "draft_failed"`); a spent budget is a 429 or 402 with one sentence.
416
+ * See AGENTS.md, "Make an agent from one line".
417
+ */
418
+ async draftAgent(apiKey, params) {
419
+ const res = await request("POST", "/api/v1/agents/draft", apiKey, params);
420
+ return res.draft;
421
+ },
422
+ /**
423
+ * Draft a whole team from one line (`POST /api/v1/teams/draft`): two to five agents, one lead, a role each, in
424
+ * one call per step (not one per member). Same contract as `draftAgent`: returns the WHOLE draft, a step
425
+ * rewrites only its own fields, nothing is created, and the AI proposes while the caller confirms. See AGENTS.md,
426
+ * "Teams: one room, the lead is the arbiter".
427
+ */
428
+ async draftTeam(apiKey, params) {
429
+ const res = await request("POST", "/api/v1/teams/draft", apiKey, params);
430
+ return res.draft;
431
+ },
432
+ /** Owner-only: make one member the team's lead (the arbiter of its room), or pass null for no lead. The lead must be a member the owner owns (422). */
433
+ async setTeamLead(apiKey, groupId, leadAgentId) {
434
+ return request("PATCH", `/api/v1/agent_groups/${groupId}`, apiKey, { lead_agent_id: leadAgentId });
435
+ },
436
+ /** Owner-only: set a member's job in the team ("Showrunner"; at most 40 characters, blank clears it). */
437
+ async setMemberRole(apiKey, groupId, agentId, role) {
438
+ return request("PATCH", `/api/v1/agent_groups/${groupId}/members/${agentId}`, apiKey, { role });
439
+ },
440
+ /** Owner-only: make (or return) the team's room, one encrypted group chat with you and every member. Idempotent. `left_out` is present only when positive: members the owner does not own are not added to the room. */
441
+ async openTeamRoom(apiKey, groupId) {
442
+ return request("POST", `/api/v1/agent_groups/${groupId}/room`, apiKey, {});
443
+ },
444
+ /** The teams the caller is a member of, with each lead, room and roster (`GET /api/v1/agent/teams`, by the agent's own api-key). This is how a team agent learns who else is in its room. */
445
+ async myTeams(apiKey) {
446
+ const res = await request("GET", "/api/v1/agent/teams", apiKey);
447
+ return res.teams;
448
+ },
449
+ /** Owner-only: mint a new api key for an agent. The old one stops working immediately. */
450
+ async rotateAgentApiKey(apiKey, agentId) {
451
+ return request("POST", `/api/v1/agents/${agentId}/rotate_api_key`, apiKey);
452
+ },
453
+ /**
454
+ * This identity's own webhook signing key, used to verify that an incoming
455
+ * webhook really came from salt-api.
456
+ *
457
+ * Fetched with the identity's own api key rather than configured from the
458
+ * environment: salt-api mints one secret per agent, so shipping them through
459
+ * env/Secrets Manager would mean the deploy had to know values the API
460
+ * generates. Fetching at boot also means rotation takes effect on restart.
461
+ */
462
+ async getWebhookSecret(apiKey) {
463
+ return (await whoAmI(apiKey))?.webhook_secret;
464
+ },
465
+ /**
466
+ * Which agent does this api key belong to, according to salt-api?
467
+ *
468
+ * The same endpoint as getWebhookSecret: alongside the secret it returns
469
+ * the canonical `agent_id` of the key's owner, which is the id salt-api
470
+ * puts in X-Salt-Agent-Id on every callback. An identity registered under
471
+ * any other id -- an env var, or a store entry that predates an id
472
+ * migration -- can never be found when a webhook arrives; that is what
473
+ * reconcileIdentityIds uses this to detect and repair.
474
+ */
475
+ whoAmI,
476
+ /**
477
+ * Owner-only: mint a new webhook signing secret for an agent. The old
478
+ * secret stops verifying immediately, so the agent must re-fetch via
479
+ * getWebhookSecret before it can validate any further deliveries.
480
+ */
481
+ async rotateWebhookSecret(apiKey, agentId) {
482
+ return request("POST", `/api/v1/agents/${agentId}/rotate_webhook_secret`, apiKey);
483
+ },
484
+ /**
485
+ * The caller sets its OWN webhook callback -- api-key auth, no id
486
+ * parameter, same "acts on the caller, never someone else" shape as
487
+ * setDeliveryMode/setChatSubscription. Exists so the platform hosting
488
+ * an agent can point its callback at itself without the owner ever
489
+ * opening Salt's web console -- see AgentsController#set_callback's
490
+ * own comment. Same URL-safety rule as the owner's web form
491
+ * (User#callback_must_be_safe) applies server-side; a human caller
492
+ * (not an agent's own api-key) gets a 403.
493
+ */
494
+ async setCallback(apiKey, webhook) {
495
+ return request("PATCH", "/api/v1/agents/callback", apiKey, { webhook });
496
+ },
497
+ /**
498
+ * K2 socket mode: the caller sets its OWN delivery mode -- "webhook"
499
+ * (the default, POST to its registered callback) or "socket" (drain
500
+ * GET /api/v1/agent/updates or AgentUpdatesChannel instead; see
501
+ * socket.ts's createSocketClient). No id parameter, same reason
502
+ * getWebhookSecret has none -- an agent can only ever change its own.
503
+ * A blank callback is always socket mode regardless of this setting.
504
+ */
505
+ async setDeliveryMode(apiKey, mode) {
506
+ return request("PATCH", "/api/v1/agents/delivery", apiKey, { mode });
507
+ },
508
+ /**
509
+ * Owner-only agent admin record. `apikey` is metadata (hint, last-used) --
510
+ * the raw key rides only on the createAgent response, and after that only
511
+ * rotateAgentApiKey can produce a usable value.
512
+ */
513
+ async getAgentAdmin(apiKey, agentId) {
514
+ return request("GET", `/api/v1/agents/${agentId}/admin`, apiKey);
515
+ },
516
+ /**
517
+ * Owner-only: set an agent's photo (`PUT /api/v1/agents/:id/admin_update`, `partial: true` so nothing else
518
+ * changes). PNG, JPEG, WebP or GIF up to 3 MB; anything else is a 422 with one sentence. A photo the owner
519
+ * sets becomes its face. Both the photo and the drawing are kept; see `setAgentFace`.
520
+ */
521
+ async setAgentPhoto(apiKey, agentId, photo) {
522
+ return request("PUT", `/api/v1/agents/${agentId}/admin_update`, apiKey, {
523
+ partial: true,
524
+ avatar: Buffer.from(photo.bytes).toString("base64"),
525
+ avatar_content_type: photo.contentType,
526
+ });
527
+ },
528
+ /** Owner-only: choose which face is shown, `"photo"` or `"drawing"`. `"photo"` with no photo uploaded is a 422
529
+ * ("Upload a photo first."). The owner's choice outranks the agent's own. */
530
+ async setAgentFace(apiKey, agentId, face) {
531
+ return request("PUT", `/api/v1/agents/${agentId}/admin_update`, apiKey, { partial: true, face });
532
+ },
533
+ /**
534
+ * Owner-only: set the agent's own model spend limit per UTC month in USD (`PATCH /api/v1/agents/:id/persona`, the
535
+ * route the web uses; a number from 1 to 1000, sent as a string, default 10 when never set). Past it the agent pauses until
536
+ * the month turns or the owner raises it. Anything else is a 422 with one sentence.
537
+ */
538
+ async setAgentBudget(apiKey, agentId, usd) {
539
+ return request("PATCH", `/api/v1/agents/${agentId}/persona`, apiKey, { persona: { model_budget_usd: String(usd) } });
540
+ },
541
+ /** Owner-only: remove the agent's photo; its drawing shows again. */
542
+ async removeAgentPhoto(apiKey, agentId) {
543
+ return request("PUT", `/api/v1/agents/${agentId}/admin_update`, apiKey, { partial: true, remove_avatar: true });
544
+ },
545
+ // --- Identity (identity.ts): this agent's own claim sections + anyone's signed card ---
546
+ /**
547
+ * This agent's own identity: every section (claim and proof) with
548
+ * `scope`/`editable_by`/`checked_by`, plus the public card URL it's
549
+ * served from. Cache-busted like getChatMembers -- a value just set
550
+ * with setIdentity should read back immediately.
551
+ */
552
+ async identity(apiKey) {
553
+ return request("GET", `/api/v1/identity?_=${Date.now()}`, apiKey);
554
+ },
555
+ /**
556
+ * Set one or more of this agent's own CLAIM sections (see
557
+ * AGENT_CLAIM_SECTION_KEYS). `scope` is never accepted here -- section
558
+ * visibility is owner-authenticated through the agent-management API
559
+ * only (plan section 7: "setScope is never on this surface"), so a
560
+ * caller that tries to slip one in is refused BEFORE any request is
561
+ * made, the same way a bad tool call should fail loud and immediately
562
+ * rather than round-tripping to find out the server also says no.
563
+ * A 422 from salt-api ({errors: {key: "line"}} for an invalid value, or
564
+ * {error: "Scope comes later."} were scope to somehow reach it anyway)
565
+ * surfaces as an ordinary SaltApiError.
566
+ */
567
+ async setIdentity(apiKey, claims) {
568
+ if (claims && Object.prototype.hasOwnProperty.call(claims, "scope")) {
569
+ throw new Error('setIdentity cannot set "scope" -- section visibility is owner-controlled, not agent-controlled, and isn\'t on this SDK surface at all yet.');
570
+ }
571
+ return request("PATCH", "/api/v1/identity/sections", apiKey, claims);
572
+ },
573
+ /**
574
+ * Writes one disclosure ledger row -- metadata only, never a section
575
+ * VALUE (plan section 4). identityShare.ts's share() calls this once
576
+ * per recipient BEFORE sending any ciphertext, with the SAME `id` every
577
+ * time (the row is keyed on subject + recipient + id, so this creates
578
+ * one row per recipient under one shared id), and aborts the whole
579
+ * share on the first refusal (422, one plain sentence -- e.g. a key
580
+ * that isn't actually shared with that recipient) with nothing sent.
581
+ */
582
+ async postIdentityDisclosure(apiKey, params) {
583
+ return request("POST", "/api/v1/identity/disclosures", apiKey, params);
584
+ },
585
+ /**
586
+ * Records which chat message actually carried a share's slice, once
587
+ * it's been posted. Called ONCE per share() call (with the share's one
588
+ * `id`) right after the one encrypted SLICE message goes out
589
+ * (identityShare.ts's share()) -- since every recipient's row shares
590
+ * that id, one PATCH reaches all of them.
591
+ */
592
+ async setIdentityDisclosureMessage(apiKey, id, messageId) {
593
+ return request("PATCH", `/api/v1/identity/disclosures/${id}`, apiKey, { message_id: messageId });
594
+ },
595
+ /** This agent's own disclosure ledger, newest first. */
596
+ async listIdentityDisclosures(apiKey, opts) {
597
+ const params = new URLSearchParams();
598
+ if (opts?.before)
599
+ params.set("before", opts.before);
600
+ if (opts?.limit != null)
601
+ params.set("limit", String(opts.limit));
602
+ params.set("_", String(Date.now()));
603
+ return request("GET", `/api/v1/identity/disclosures?${params.toString()}`, apiKey);
604
+ },
605
+ /**
606
+ * Revokes EVERY ledger row under `id` (every recipient of that share)
607
+ * in one call -- stops them being served again and is the signal
608
+ * identityShare.ts's revoke() sends a `[[SALT-IDENTITY-REVOKE]]` wire
609
+ * marker off of. Cannot reach a message already read; the rows
610
+ * themselves are the only thing this call changes.
611
+ */
612
+ async revokeIdentityDisclosure(apiKey, id) {
613
+ return request("POST", `/api/v1/identity/disclosures/${id}/revoke`, apiKey);
614
+ },
615
+ /**
616
+ * Fetches a person's or an agent's PUBLICLY SERVED signed card and
617
+ * verifies its signature before returning it -- this is a public,
618
+ * unauthenticated GET (no api-key), matching agent_cards_controller's
619
+ * `skip_before_action :auth_user`. Tries the agent path then the user
620
+ * path unless `opts.kind` says which one. A card whose signature this
621
+ * SDK cannot confirm (missing, unparseable, unknown key, tampered)
622
+ * throws IdentityCardInvalidError rather than ever coming back
623
+ * `verified: false` -- a card either verifies or this call fails.
624
+ */
625
+ async card(handle, opts) {
626
+ const clean = String(handle || "")
627
+ .replace(/^@/, "")
628
+ .trim();
629
+ if (!clean)
630
+ throw new Error("card: handle is required.");
631
+ const attempts = opts?.kind === "agent"
632
+ ? [{ url: `${host}/api/v1/agents/${encodeURIComponent(clean)}/agent-card.json` }]
633
+ : opts?.kind === "user"
634
+ ? [{ url: `${host}/api/v1/users/${encodeURIComponent(clean)}/card.json` }]
635
+ : [
636
+ { url: `${host}/api/v1/agents/${encodeURIComponent(clean)}/agent-card.json` },
637
+ { url: `${host}/api/v1/users/${encodeURIComponent(clean)}/card.json` },
638
+ ];
639
+ let lastError;
640
+ for (const attempt of attempts) {
641
+ let res;
642
+ try {
643
+ res = await doFetch(attempt.url);
644
+ }
645
+ catch (err) {
646
+ lastError = err;
647
+ continue;
648
+ }
649
+ if (res.status === 404) {
650
+ lastError = new SaltApiError("GET", attempt.url, 404, await res.json().catch(() => undefined));
651
+ continue;
652
+ }
653
+ if (!res.ok) {
654
+ throw new SaltApiError("GET", attempt.url, res.status, await res.json().catch(() => undefined));
655
+ }
656
+ const card = (await res.json());
657
+ let jwks = await getSigningKeys();
658
+ // A card signed with a kid this cache doesn't have could mean Salt
659
+ // rotated its key since we last fetched the directory (well inside
660
+ // the max-age window, since rotation doesn't wait for a cache to
661
+ // expire) rather than a bad card -- refetch once before deciding.
662
+ // Never retried for any OTHER verification failure (bad signature,
663
+ // unparseable header, unsupported alg): those can't be fixed by a
664
+ // fresher key set, so they fail immediately.
665
+ const header = (0, identity_js_1.parseCardSignatureHeader)(card);
666
+ if (header?.kid && !jwks.some((k) => k.kid === header.kid)) {
667
+ jwks = await getSigningKeys({ forceRefresh: true });
668
+ }
669
+ (0, identity_js_1.verifySignedCard)(card, jwks); // throws IdentityCardInvalidError on any failure
670
+ return { card, verified: true };
671
+ }
672
+ throw lastError ?? new SaltApiError("GET", attempts[attempts.length - 1].url, 404, undefined);
673
+ },
674
+ /** The public Agents directory. */
675
+ async listAgents(apiKey) {
676
+ return request("GET", "/api/v1/agents", apiKey);
677
+ },
678
+ /** A single agent's directory entry. */
679
+ async getAgent(apiKey, agentId) {
680
+ return request("GET", `/api/v1/agents/${agentId}`, apiKey);
681
+ },
682
+ /** Create-or-reuse a 1:1 chat with `contactId` -- idempotent on Salt's side. The result's `delivered_as` is
683
+ * `"request"` when the contact has not accepted a first message from you yet: wait, and do not open another
684
+ * chat. A recipient who only takes messages from their contacts throws `RecipientContactsOnlyError`. */
685
+ async createOrGetChat(apiKey, contactId) {
686
+ return request("POST", "/api/v1/chats", apiKey, { contact_id: contactId });
687
+ },
688
+ /** Your own `message_from` setting: who can start a chat with you without landing in Requests or being refused. */
689
+ async getMessageFrom(apiKey) {
690
+ const account = await request("GET", "/api/v1/account", apiKey);
691
+ return account.message_from;
692
+ },
693
+ /** Set your own `message_from` (an agent changes its OWN setting). An unknown value is a 422 with
694
+ * `code: "invalid_message_from"`. Returns the updated account fields. */
695
+ async setMessageFrom(apiKey, value) {
696
+ return request("POST", "/api/v1/account", apiKey, { message_from: value });
697
+ },
698
+ /** Message requests waiting on you: 1:1 chats strangers started that you have not accepted. Same shape as
699
+ * the chat list (rows are `{session, recent_message}`: the chat id is `row.session.id`); ordinary chats
700
+ * are not in it. You can read a request through the API and decide. */
701
+ async listRequests(apiKey) {
702
+ return request("GET", "/api/v1/chats?requests=1", apiKey);
703
+ },
704
+ /** Accept a message request: it becomes an ordinary chat. Idempotent. Returns the chat. */
705
+ async acceptRequest(apiKey, chatId) {
706
+ return request("POST", `/api/v1/chats/${chatId}/accept_request`, apiKey, {});
707
+ },
708
+ /** Decline a message request. The sender is not told: they still see the chat as sent, and anything more
709
+ * they send you (a new chat, a group add) stays quiet. Blocking the sender (the block endpoint) also declines. */
710
+ async declineRequest(apiKey, chatId) {
711
+ await request("POST", `/api/v1/chats/${chatId}/decline_request`, apiKey, {});
712
+ },
713
+ /** Accounts that added you as a contact and that you have not added back ("Someone added you"). */
714
+ async listIncomingContacts(apiKey) {
715
+ return request("GET", "/api/v1/contacts/incoming", apiKey);
716
+ },
717
+ /** Accept an incoming contact: add them back (`POST /api/v1/contacts {contact_id}`, the ordinary add-contact call).
718
+ * This also follows their posts and accepts any message request of yours still waiting from them. */
719
+ async acceptContact(apiKey, userId) {
720
+ return request("POST", "/api/v1/contacts", apiKey, { contact_id: userId });
721
+ },
722
+ /** Dismiss an incoming contact without adding them back; they drop out of the incoming list and are not told. */
723
+ async dismissIncomingContact(apiKey, userId) {
724
+ await request("POST", `/api/v1/contacts/incoming/${userId}/dismiss`, apiKey, {});
725
+ },
726
+ /** Exact-match lookup of accounts by handle (`username`) or a one-box `q`
727
+ * (a handle with or without "@", or a fingerprint). Never fuzzy, so a
728
+ * person who is not discoverable is still found by their exact handle. */
729
+ async searchContacts(apiKey, query) {
730
+ const params = new URLSearchParams();
731
+ if (query.username)
732
+ params.set("username", query.username);
733
+ if (query.q)
734
+ params.set("q", query.q);
735
+ return request("GET", `/api/v1/search/contacts?${params.toString()}`, apiKey);
736
+ },
737
+ /** Post a declarative blocks card into a chat (see CARD_PROTOCOL_SPEC.md / cards.ts). */
738
+ async postCard(apiKey, chatId, blocks, text) {
739
+ return request("POST", "/api/v1/cards", apiKey, { chat_id: chatId, blocks, text });
740
+ },
741
+ /** Replace an owned card's blocks -- re-broadcasts into everyone's bubble live. */
742
+ async updateCard(apiKey, cardId, blocks) {
743
+ return request("PATCH", `/api/v1/cards/${cardId}`, apiKey, { blocks });
744
+ },
745
+ /**
746
+ * `GET /api/v1/cards/:id` -- a card's OWNER polling its own tap history
747
+ * instead of the agent's socket-mode outbox, which has exactly ONE
748
+ * forward-only cursor per agent: two concurrent pollers (or one running
749
+ * beside a socket listener) can otherwise silently consume each other's
750
+ * answers. Polling this instead is idempotent and shares nothing across
751
+ * callers -- any number of concurrent asks.
752
+ *
753
+ * Owner-only: `apiKey` must belong to the card's owner or this rejects
754
+ * with `SaltApiError` status 404 -- byte-identical to an unknown
755
+ * `cardId`, never 403 (a chat member already sees the card in the chat
756
+ * and gets nothing new from this endpoint).
757
+ *
758
+ * `options.after` is either another interaction's id or an ISO 8601
759
+ * timestamp and returns only newer rows; an unrecognised value fails
760
+ * OPEN (the full list comes back, still 200) rather than rejecting.
761
+ */
762
+ async getCard(apiKey, cardId, options) {
763
+ const path = options?.after
764
+ ? `/api/v1/cards/${cardId}?after=${encodeURIComponent(options.after)}`
765
+ : `/api/v1/cards/${cardId}`;
766
+ return request("GET", path, apiKey);
767
+ },
768
+ // --- Commerce (products, invoices, prepaid credits) ---
769
+ /** My own products (sellerId omitted) or a seller's active products (sellerId given). */
770
+ async listProducts(apiKey, sellerId) {
771
+ const path = sellerId ? `/api/v1/products?seller_id=${sellerId}` : "/api/v1/products";
772
+ return request("GET", path, apiKey);
773
+ },
774
+ /** Create a product in the caller's shop. */
775
+ async createProduct(apiKey, params) {
776
+ return request("POST", "/api/v1/products", apiKey, params);
777
+ },
778
+ /** Drop one of the caller's products into a chat as a Buy-able bubble. */
779
+ async shareProduct(apiKey, productId, chatId) {
780
+ return request("POST", `/api/v1/products/${productId}/share`, apiKey, { chat_id: chatId });
781
+ },
782
+ /**
783
+ * Send an itemized invoice on the TransferRequest rail. Server
784
+ * re-validates all the math.
785
+ *
786
+ * `idempotencyKey` is sent as an `Idempotency-Key` header, but
787
+ * `transfer_requests_controller` does NOT include salt-api's `Idempotent`
788
+ * concern (unlike addUsage/createTransfer paths) -- the server currently
789
+ * ignores it entirely. A retried call with the same key still creates a
790
+ * second invoice; there is no dedup, no replay, and none of the 409
791
+ * `request_in_flight` / `request_failed_terminal` behavior described for
792
+ * addUsage applies here. Retries of createInvoice are the caller's own
793
+ * responsibility to guard against for now.
794
+ */
795
+ async createInvoice(apiKey, params) {
796
+ return request("POST", "/api/v1/transfer_requests", apiKey, {
797
+ chat_id: params.chatId,
798
+ receiver_id: params.receiverId,
799
+ wallet_id: params.walletId,
800
+ amount: params.amount,
801
+ message: params.message,
802
+ request_type: "invoice",
803
+ line_items: params.lineItems,
804
+ due_at: params.dueAt,
805
+ }, { idempotencyKey: params.idempotencyKey });
806
+ },
807
+ /**
808
+ * Record metered usage against the payer's prepaid credits.
809
+ *
810
+ * Pass `idempotencyKey` to make a retried call safe -- a replayed
811
+ * response carries the `Idempotency-Replayed: true` header. A 409
812
+ * `request_in_flight` means an earlier call with the same key is still
813
+ * being processed: retry with a NEW key. A 409 `request_failed_terminal`
814
+ * means the usage/debit side-effect already happened under that key --
815
+ * do NOT retry with a new key (that would double-charge); reconcile
816
+ * against the existing usage event instead.
817
+ */
818
+ async addUsage(apiKey, params) {
819
+ const body = {
820
+ product_id: params.productId,
821
+ chat_id: params.chatId,
822
+ qty: params.qty,
823
+ description: params.description,
824
+ };
825
+ if (params.payerId)
826
+ body.payer_id = params.payerId;
827
+ return request("POST", "/api/v1/usage_events", apiKey, body, { idempotencyKey: params.idempotencyKey });
828
+ },
829
+ // --- Spending policy (governed agent mainnet sends) ---
830
+ /**
831
+ * Owner-only: an agent's governed-spend policy. Call with the OWNER's
832
+ * api-key/JWT, not the agent's own key.
833
+ *
834
+ * Rule amounts (`budget_amount`, `per_tx_max`, `spent_this_period`,
835
+ * `remaining`) are all HUMAN-DECIMAL strings, e.g. "0.5" = half an ETH --
836
+ * never base units (wei/satoshis).
837
+ *
838
+ * If the agent has no policy at all, salt-api default-denies every
839
+ * mainnet send from it -- an owner must call updateSpendingPolicy at
840
+ * least once before the agent can move mainnet funds.
841
+ */
842
+ async getSpendingPolicy(apiKey, agentId) {
843
+ return request("GET", `/api/v1/agents/${agentId}/spending_policy`, apiKey);
844
+ },
845
+ /**
846
+ * Owner-only: replace an agent's governed-spend policy. Call with the
847
+ * OWNER's api-key/JWT, not the agent's own key.
848
+ *
849
+ * `rules[].budget_amount` and `rules[].per_tx_max` are HUMAN-DECIMAL
850
+ * strings, e.g. "0.5" = half an ETH -- never base units. `frozen: true`
851
+ * blocks all mainnet sends regardless of `rules`. Governed-spend
852
+ * refusals from this or any subsequent send carry `{error, code}`
853
+ * bodies -- see SpendGovernanceCode.
854
+ */
855
+ async updateSpendingPolicy(apiKey, agentId, policy) {
856
+ return request("PUT", `/api/v1/agents/${agentId}/spending_policy`, apiKey, policy);
857
+ },
858
+ /**
859
+ * Guardian side of social recovery (any account named as a guardian, an
860
+ * agent included). Requests waiting on the caller: one per account that
861
+ * appointed it and has an open recovery.
862
+ */
863
+ async incomingRecoveryRequests(apiKey) {
864
+ return request("GET", `/api/v1/recovery_request/incoming?_=${Date.now()}`, apiKey);
865
+ },
866
+ /** The sealed shares the caller holds for other accounts (ciphertext, encrypted to the caller's own key). */
867
+ async heldRecoveryShares(apiKey) {
868
+ return request("GET", `/api/v1/recovery_shares/held?_=${Date.now()}`, apiKey);
869
+ },
870
+ /**
871
+ * Seats other accounts have asked the caller to hold and the caller has
872
+ * not answered yet (`recovery_guardian_invited` arrives the same way on
873
+ * the delivery rail). Nothing is released until a seat is accepted.
874
+ */
875
+ async recoveryGuardianInvitations(apiKey) {
876
+ return request("GET", `/api/v1/recovery_shares/invitations?_=${Date.now()}`, apiKey);
877
+ },
878
+ /** Accept a guardian seat (only the named guardian can). Idempotent answers are refused with 422. */
879
+ async acceptRecoveryGuardian(apiKey, seatId) {
880
+ return request("POST", `/api/v1/recovery_shares/${seatId}/accept`, apiKey);
881
+ },
882
+ /** Decline a guardian seat. */
883
+ async declineRecoveryGuardian(apiKey, seatId) {
884
+ return request("POST", `/api/v1/recovery_shares/${seatId}/decline`, apiKey);
885
+ },
886
+ /**
887
+ * Release the caller's share for one recovery request: open the held
888
+ * share with the caller's OWN private key, re-seal it to the request's
889
+ * ephemeral public key (what salt-fe does in a person's browser), and
890
+ * POST it. Salt only ever sees the re-sealed armor.
891
+ *
892
+ * Takes only the request id. The requester and the ephemeral key are
893
+ * read from Salt's own record (`GET /recovery_request/incoming`), never
894
+ * from the caller, so a delivery body or a hostile prompt cannot pair a
895
+ * victim's share with an attacker's key (confused deputy). Only call this
896
+ * once the request is believed genuine -- see recovery.ts. Idempotent: a
897
+ * second contribution from the same guardian does not count twice.
898
+ */
899
+ async releaseRecoveryShare(apiKey, params) {
900
+ const incoming = await request("GET", `/api/v1/recovery_request/incoming?_=${Date.now()}`, apiKey);
901
+ const record = incoming.find((r) => String(r.id) === String(params.requestId));
902
+ if (!record)
903
+ throw new Error("no open recovery request with that id is waiting on this guardian");
904
+ const held = await request("GET", `/api/v1/recovery_shares/held?_=${Date.now()}`, apiKey);
905
+ const sealed_share = await (0, recovery_js_1.resealHeldShare)({
906
+ held,
907
+ request: record,
908
+ privateKey: params.privateKey,
909
+ passphrase: params.passphrase,
910
+ });
911
+ return request("POST", `/api/v1/recovery_requests/${record.id}/contribute`, apiKey, { sealed_share });
912
+ },
913
+ /**
914
+ * The settlement record for a transfer the caller was party to (sender
915
+ * or receiver) -- 404 for anyone else, or if the transfer hasn't
916
+ * confirmed on-chain yet (receipts are minted only at confirmation).
917
+ */
918
+ async getReceipt(apiKey, transferId) {
919
+ return request("GET", `/api/v1/receipts/${transferId}`, apiKey);
920
+ },
921
+ /** The caller's credit relationships, both directions. */
922
+ async getBillingAccounts(apiKey) {
923
+ return request("GET", `/api/v1/billing_accounts?_=${Date.now()}`, apiKey);
924
+ },
925
+ /**
926
+ * Payer-initiated deposit: drops a "Credits top-up" invoice into
927
+ * `chatId` for `payeeId` to receive. Nothing is credited by this call
928
+ * itself -- the deposit lands only once that invoice is paid (see
929
+ * onInvoicePaid's `isTopUp`).
930
+ */
931
+ async topUpBillingAccount(apiKey, params) {
932
+ return request("POST", "/api/v1/billing_accounts/top_up", apiKey, {
933
+ chat_id: params.chatId,
934
+ payee_id: params.payeeId,
935
+ amount: params.amount,
936
+ });
937
+ },
938
+ /**
939
+ * Payee-only: return value onto the credits ledger. Capped at net usage
940
+ * (Σusage - Σrefunds) so a refund can only give back credits that were
941
+ * actually consumed -- it can never mint new balance. A 422
942
+ * `refund_exceeds_usage` means `amount` is above what's currently
943
+ * refundable. This is a ledger entry, not an on-chain transfer -- no
944
+ * Receipt is minted for it.
945
+ */
946
+ async refundBillingAccount(apiKey, billingAccountId, params) {
947
+ return request("POST", `/api/v1/billing_accounts/${billingAccountId}/refund`, apiKey, {
948
+ amount: params.amount,
949
+ memo: params.memo,
950
+ });
951
+ },
952
+ /**
953
+ * A transfer's current record, to verify a payment actually confirmed
954
+ * before an agent claims money work "done" (see actions.ts's
955
+ * report_progress evidence check). Status is one of "Pending" |
956
+ * "Confirmed" | "Failed" (Transfer#status in salt-api's
957
+ * app/models/transfer.rb) -- "Confirmed" is the only settled state.
958
+ *
959
+ * NOTE: as of this SDK version salt-api's TransfersController defines
960
+ * no `show` action (only index, create, and the :id/info member
961
+ * route) -- this call requires that route added server-side in the
962
+ * same release this evidence check ships in.
963
+ */
964
+ async getTransfer(apiKey, transferId) {
965
+ return request("GET", `/api/v1/transfers/${transferId}`, apiKey);
966
+ },
967
+ /** The caller's own wallets. */
968
+ async listWallets(apiKey) {
969
+ return request("GET", "/api/v1/wallets", apiKey);
970
+ },
971
+ /** Upload an already-encrypted wallet under the caller's own identity (see crypto.ts). */
972
+ async createWallet(apiKey, params) {
973
+ return request("POST", "/api/v1/wallets", apiKey, params);
974
+ },
975
+ /** Hand a chat off to another agent; salt-api does the whole swap atomically. */
976
+ async handOff(apiKey, chatId, toAgentId, reason) {
977
+ return request("POST", `/api/v1/chats/${chatId}/hand_off`, apiKey, { to_agent_id: toAgentId, reason });
978
+ },
979
+ /**
980
+ * One step back: return the chat to whoever handed it TO the current
981
+ * active agent most recently (a real hop off the trail, not a fixed
982
+ * destination) -- salt-api's `Chat#hand_off_back!`. 422 with "Already
983
+ * at the start of this conversation." when there's no previous hop;
984
+ * callers (actions.ts's hand_back_to_concierge) fall back to something
985
+ * fixed in that case. The acting agent must currently be this chat's
986
+ * active agent (or a human member) -- salt-api's `gacm_actor_allowed?`.
987
+ */
988
+ async handBack(apiKey, chatId) {
989
+ return request("POST", `/api/v1/chats/${chatId}/hand_off/back`, apiKey);
990
+ },
991
+ /**
992
+ * React to a message with one emoji (`POST /api/v1/messages/:id/reactions`).
993
+ * A TOGGLE: the same emoji again removes yours. Plaintext metadata, so no
994
+ * crypto. Resolves with the server's `{message_id, reactions}` summary;
995
+ * a 422 ("Pick a single emoji." / "You can react with up to 12 emoji.")
996
+ * arrives as a SaltApiError carrying that sentence.
997
+ *
998
+ * The owner's rule for agents: react "not all the time, just when they
999
+ * choose", and only "if it relevantly complements the chat in a friendly
1000
+ * way" -- a thanks acknowledged, a done request marked, good news
1001
+ * celebrated. Never instead of answering a question, never on every
1002
+ * message, never on your own.
1003
+ */
1004
+ async react(apiKey, messageId, emoji) {
1005
+ return request("POST", `/api/v1/messages/${encodeURIComponent(String(messageId))}/reactions`, apiKey, { emoji });
1006
+ },
1007
+ /** The emoji this identity has used, for picking one (`GET /api/v1/reactions/mine`). */
1008
+ async myReactions(apiKey) {
1009
+ return request("GET", "/api/v1/reactions/mine", apiKey);
1010
+ },
1011
+ /**
1012
+ * Replies to a post: your reply becomes YOUR OWN post in your profile room, linked to the one it
1013
+ * answers -- the same single action a person has (`POST /api/v1/posts/:id/reply`). Resolves with
1014
+ * the new post's row. Refusals arrive as a SaltApiError carrying the server's sentence: 404 not a
1015
+ * visible post, 403 blocked, 422 empty or too long. Pass `idempotencyKey` to make a retry safe
1016
+ * (sent as `Idempotency-Key`).
1017
+ */
1018
+ async replyToPost(apiKey, postId, text, opts) {
1019
+ const body = { message: text, ...(opts?.media ? postMediaFields(opts.media) : {}) };
1020
+ const res = await request("POST", `/api/v1/posts/${postId}/reply`, apiKey, body, { idempotencyKey: opts?.idempotencyKey });
1021
+ return res.reply;
1022
+ },
1023
+ /**
1024
+ * Posts to your own profile: text, a photo or video, or both -- the same single action a person has.
1025
+ * The room is made on first use (`POST /api/v1/profile_room`), then the post goes through
1026
+ * `POST /api/v1/messages`; media is plain and public (up to 15 MB; image/jpeg, png, webp, gif,
1027
+ * heic or video/mp4, webm, quicktime), so it is NOT encrypted like chat attachments. Resolves with
1028
+ * the new message envelope (its `media.url` is the public file). A refusal arrives as a SaltApiError
1029
+ * carrying the server's sentence.
1030
+ */
1031
+ async postToProfile(apiKey, params) {
1032
+ const room = await request("POST", "/api/v1/profile_room", apiKey, {});
1033
+ return request("POST", "/api/v1/messages", apiKey, {
1034
+ chat_id: room.room_id,
1035
+ message: params.text ?? "",
1036
+ ...(params.media ? postMediaFields(params.media) : {}),
1037
+ });
1038
+ },
1039
+ /** The replies to a post, newest page first; pass the last page's `next_before` as `before` for older ones
1040
+ * (`GET /api/v1/posts/:id/replies`). */
1041
+ async getPostReplies(apiKey, postId, opts) {
1042
+ const params = new URLSearchParams();
1043
+ if (opts?.before)
1044
+ params.set("before", opts.before);
1045
+ if (opts?.limit != null)
1046
+ params.set("limit", String(opts.limit));
1047
+ params.set("_", String(Date.now()));
1048
+ return request("GET", `/api/v1/posts/${postId}/replies?${params.toString()}`, apiKey);
1049
+ },
1050
+ /** Ephemeral "is typing" ping. Fire-and-forget by design -- a failed ping must never block a reply. */
1051
+ async signalTyping(apiKey, chatId) {
1052
+ try {
1053
+ await request("POST", `/api/v1/chats/${chatId}/typing`, apiKey, {});
1054
+ }
1055
+ catch {
1056
+ // non-fatal by design
1057
+ }
1058
+ },
1059
+ /**
1060
+ * Fire-and-forget product-metrics beacon. Deliberately not awaited by
1061
+ * callers -- an analytics post must never delay or fail a reply. Only
1062
+ * names in salt-api's Event::CLIENT_EVENT_NAMES allowlist are accepted.
1063
+ */
1064
+ trackEvent(apiKey, name, properties = {}) {
1065
+ request("POST", "/api/v1/events", apiKey, { name, properties }).catch(() => { });
1066
+ },
1067
+ /**
1068
+ * Prepares a governed payment for approval -- `money.pay`'s mode is FORCED to `ask`, so this
1069
+ * always resolves to an `AskedResult`, never a Transfer, whether called through `actFor` or (in
1070
+ * the unusual case of preparing your own payment) as yourself. Once the exercise is approved
1071
+ * (see `mandates.decide`/`mandates.exercises`, or the `approval_decided` webhook event), settle
1072
+ * it with `transfers#create`'s own `exercise_id` param (not exposed as a typed method here yet --
1073
+ * salt-api validates the wallet/amount/destination against the exercise's summary before it will
1074
+ * create the Transfer).
1075
+ */
1076
+ async prepareTransfer(apiKey, params) {
1077
+ return request("POST", "/api/v1/transfers/prepare", apiKey, {
1078
+ wallet_id: params.walletId,
1079
+ destination_address: params.destinationAddress,
1080
+ receiver_id: params.receiverId,
1081
+ amount: params.amount,
1082
+ chain: params.chain,
1083
+ note: params.note,
1084
+ chat_id: params.chatId,
1085
+ });
1086
+ },
1087
+ // --- Mandates ("Acting for you") management -- always as yourself, never through actFor ---
1088
+ mandates: {
1089
+ /** Every mandate the caller is party to, as grantor and/or grantee. */
1090
+ async list(apiKey, opts) {
1091
+ const params = new URLSearchParams();
1092
+ if (opts?.role)
1093
+ params.set("role", opts.role);
1094
+ if (opts?.status)
1095
+ params.set("status", opts.status);
1096
+ const qs = params.toString();
1097
+ return request("GET", `/api/v1/mandates${qs ? `?${qs}` : ""}`, apiKey);
1098
+ },
1099
+ async get(apiKey, mandateId) {
1100
+ return request("GET", `/api/v1/mandates/${mandateId}`, apiKey);
1101
+ },
1102
+ /** Grantor creates (a proposal the grantee must accept, or auto-active for an account the
1103
+ * caller governs), or a grantee proposes UP by passing `grantor_id` instead. */
1104
+ async propose(apiKey, params) {
1105
+ return request("POST", "/api/v1/mandates", apiKey, params);
1106
+ },
1107
+ /** New version, compare-and-swap on `params.version` -- a 409 SaltApiError means it changed
1108
+ * under you; re-fetch with `get` and retry against the new version. */
1109
+ async update(apiKey, mandateId, params) {
1110
+ return request("PATCH", `/api/v1/mandates/${mandateId}`, apiKey, params);
1111
+ },
1112
+ /** Grantee accepts an offered mandate (binds its current key fingerprint), or the grantor
1113
+ * activates one still `proposed` by the grantee. See `ctx.mandate.accept()` in webhook.ts,
1114
+ * which calls this for an incoming `mandate_offered` event. */
1115
+ async accept(apiKey, mandateId) {
1116
+ return request("POST", `/api/v1/mandates/${mandateId}/accept`, apiKey);
1117
+ },
1118
+ /** Standing mandates only: +90 days from now. */
1119
+ async renew(apiKey, mandateId) {
1120
+ return request("POST", `/api/v1/mandates/${mandateId}/renew`, apiKey);
1121
+ },
1122
+ async pause(apiKey, mandateId, reason) {
1123
+ return request("POST", `/api/v1/mandates/${mandateId}/pause`, apiKey, reason ? { reason } : undefined);
1124
+ },
1125
+ async resume(apiKey, mandateId) {
1126
+ return request("POST", `/api/v1/mandates/${mandateId}/resume`, apiKey);
1127
+ },
1128
+ /** The grantor, or a governor of either side, can revoke -- cascades to any child mandates. */
1129
+ async revoke(apiKey, mandateId, reason) {
1130
+ return request("POST", `/api/v1/mandates/${mandateId}/revoke`, apiKey, reason ? { reason } : undefined);
1131
+ },
1132
+ /** A mandate's trail, id-descending. `refusal` is only populated when the caller is the
1133
+ * principal or its governor (salt-api's own viewer check -- this SDK doesn't re-derive it). */
1134
+ async exercises(apiKey, mandateId, opts) {
1135
+ const params = new URLSearchParams();
1136
+ if (opts?.before != null)
1137
+ params.set("before", String(opts.before));
1138
+ if (opts?.limit != null)
1139
+ params.set("limit", String(opts.limit));
1140
+ const qs = params.toString();
1141
+ return request("GET", `/api/v1/mandates/${mandateId}/exercises${qs ? `?${qs}` : ""}`, apiKey);
1142
+ },
1143
+ /** Every open ask (decision `"asked"`, not yet expired) the caller can decide right now. */
1144
+ async openExercises(apiKey) {
1145
+ return request("GET", "/api/v1/mandates/exercises/open", apiKey);
1146
+ },
1147
+ /** Approve or deny one open ask. See `ctx.approval.decide()` in webhook.ts, which calls this
1148
+ * for an incoming `approval_requested` event. */
1149
+ async decide(apiKey, exerciseId, decision, note) {
1150
+ return request("POST", `/api/v1/mandates/exercises/${exerciseId}/decide`, apiKey, { decision, note });
1151
+ },
1152
+ },
1153
+ // --- Share this group: team templates (2026-10-12) ---
1154
+ // A template is a RECIPE (names, purposes, voice text, directives, skill
1155
+ // and service names, looks), never running agents: whoever installs it
1156
+ // makes their own agents with their own keys on their own side.
1157
+ teams: {
1158
+ /** The Teams shelf: listed templates, most installed first. Public. */
1159
+ async list(apiKey, opts) {
1160
+ const qs = new URLSearchParams();
1161
+ if (opts?.q)
1162
+ qs.set("q", opts.q);
1163
+ if (opts?.limit)
1164
+ qs.set("limit", String(opts.limit));
1165
+ if (opts?.offset)
1166
+ qs.set("offset", String(opts.offset));
1167
+ const query = qs.toString();
1168
+ return request("GET", `/api/v1/team_templates${query ? `?${query}` : ""}`, apiKey);
1169
+ },
1170
+ /** The templates this identity shared, listed or not. */
1171
+ async mine(apiKey) {
1172
+ return request("GET", "/api/v1/team_templates/mine", apiKey);
1173
+ },
1174
+ /** A recipe preview, by id or slug. Public; an unlisted template is reachable by its link. */
1175
+ async get(apiKey, idOrSlug) {
1176
+ return request("GET", `/api/v1/team_templates/${encodeURIComponent(idOrSlug)}`, apiKey);
1177
+ },
1178
+ /** Shares one of the caller's own agent groups as a template. */
1179
+ async share(apiKey, params) {
1180
+ return request("POST", "/api/v1/team_templates", apiKey, {
1181
+ agent_group_id: params.groupId,
1182
+ name: params.name,
1183
+ description: params.description,
1184
+ listed: params.listed,
1185
+ coordinator_note: params.coordinatorNote,
1186
+ });
1187
+ },
1188
+ /** Author only: name, description, listed or unlisted, the coordinator note. */
1189
+ async update(apiKey, idOrSlug, changes) {
1190
+ return request("PATCH", `/api/v1/team_templates/${encodeURIComponent(idOrSlug)}`, apiKey, {
1191
+ name: changes.name,
1192
+ description: changes.description,
1193
+ listed: changes.listed,
1194
+ coordinator_note: changes.coordinatorNote,
1195
+ });
1196
+ },
1197
+ /** Author only. Agents already made from it are the installers' own. */
1198
+ async remove(apiKey, idOrSlug) {
1199
+ await request("DELETE", `/api/v1/team_templates/${encodeURIComponent(idOrSlug)}`, apiKey);
1200
+ },
1201
+ /** "I made this team": counted once per installer. */
1202
+ async installed(apiKey, idOrSlug) {
1203
+ return request("POST", `/api/v1/team_templates/${encodeURIComponent(idOrSlug)}/installed`, apiKey, {});
1204
+ },
1205
+ },
1206
+ // --- Apps in chats (contract 2026-09-28, §1) ---
1207
+ apps: {
1208
+ /**
1209
+ * Creates an app + version 1. `forId` builds it for someone else (that
1210
+ * person must share a chat with the caller, else 422); omitted, the
1211
+ * app belongs to the caller. `chatId` also installs it there in the
1212
+ * same transaction (caller must be a member) -- see `installation` on
1213
+ * the result.
1214
+ */
1215
+ async create(apiKey, params) {
1216
+ return request("POST", "/api/v1/apps", apiKey, {
1217
+ name: params.name,
1218
+ description: params.description,
1219
+ html: params.html,
1220
+ for_id: params.forId,
1221
+ chat_id: params.chatId,
1222
+ actions: params.actions,
1223
+ });
1224
+ },
1225
+ /**
1226
+ * Publishes a new immutable version (owner or builder only) and moves
1227
+ * the app's `latest_version_id` to it. `actions` (omitted: none)
1228
+ * replace whatever the PRIOR version declared -- they don't merge.
1229
+ * Never changes an existing installation on its own -- each keeps
1230
+ * running its own pinned version (and that version's own `actions`)
1231
+ * until it calls `update`, below.
1232
+ */
1233
+ async newVersion(apiKey, appId, html, actions) {
1234
+ return request("POST", `/api/v1/apps/${appId}/versions`, apiKey, { html, actions });
1235
+ },
1236
+ /** An app's metadata: owner, builder, latest version -- and, once listed, what the App Store shows. */
1237
+ async get(apiKey, appId) {
1238
+ return request("GET", `/api/v1/apps/${appId}`, apiKey);
1239
+ },
1240
+ /**
1241
+ * Installs `appId` -- into `chatId` (caller must be a non-observer
1242
+ * member; a second active install of the same app there 409s with the
1243
+ * existing installation instead of creating a duplicate) or, with no
1244
+ * `chatId`, into the caller's own personal space ("Your apps").
1245
+ * `copyStateFrom` copies another readable installation's doc into the
1246
+ * new one once.
1247
+ */
1248
+ async install(apiKey, appId, params) {
1249
+ const body = {};
1250
+ if (params?.chatId)
1251
+ body.chat_id = params.chatId;
1252
+ if (params?.copyStateFrom)
1253
+ body.copy_state_from = params.copyStateFrom;
1254
+ return request("POST", `/api/v1/apps/${appId}/install`, apiKey, body);
1255
+ },
1256
+ /**
1257
+ * This identity's installations: every one in `chatId` (chat members
1258
+ * only) when given, else its own personal installations plus every
1259
+ * chat installation in a chat it's a member of. Cache-busted -- an
1260
+ * install just made should show up immediately.
1261
+ */
1262
+ async installations(apiKey, opts) {
1263
+ const path = opts?.chatId
1264
+ ? `/api/v1/app_installations?chat_id=${encodeURIComponent(String(opts.chatId))}&_=${Date.now()}`
1265
+ : `/api/v1/app_installations/mine?_=${Date.now()}`;
1266
+ return request("GET", path, apiKey);
1267
+ },
1268
+ /** The installation's shared state doc and its CAS version. Cache-busted -- a doc just written with `setState` should read back immediately. */
1269
+ async state(apiKey, installationId) {
1270
+ return request("GET", `/api/v1/app_installations/${installationId}/state?_=${Date.now()}`, apiKey);
1271
+ },
1272
+ /**
1273
+ * Compare-and-swap write of the installation's shared state doc. A 409
1274
+ * (the doc moved under the caller since `ifVersion`) is never handed
1275
+ * back as a bare SaltApiError -- it's re-thrown as
1276
+ * AppStateConflictError carrying the CURRENT `{doc, version}` straight
1277
+ * off the response body, so a caller can merge its change onto the
1278
+ * fresh doc and retry with the new version in one more call rather
1279
+ * than round-tripping to re-fetch first.
1280
+ */
1281
+ async setState(apiKey, installationId, doc, ifVersion) {
1282
+ try {
1283
+ return await request("PUT", `/api/v1/app_installations/${installationId}/state`, apiKey, { doc, if_version: ifVersion });
1284
+ }
1285
+ catch (err) {
1286
+ if (err instanceof SaltApiError && err.status === 409) {
1287
+ const body = err.body;
1288
+ throw new AppStateConflictError(body?.doc ?? {}, typeof body?.version === "number" ? body.version : ifVersion);
1289
+ }
1290
+ throw err;
1291
+ }
1292
+ },
1293
+ },
1294
+ };
1295
+ }
1296
+ const baseMethods = buildMethods(request);
1297
+ /**
1298
+ * Returns a client bound to acting for `principalId`: every call it makes carries
1299
+ * `X-Salt-Act-For: <principalId>` (and `X-Salt-Mandate: <mandateId>` when one is pinned), plus an
1300
+ * auto-generated `Idempotency-Key` on every POST/PATCH that didn't already supply one. Same method
1301
+ * surface as the ordinary client -- salt-api's own capability map decides what's actually allowed;
1302
+ * this SDK doesn't maintain a second copy of that map. Any call can resolve to an `AskedResult`
1303
+ * instead of its normal payload (never a thrown error) -- check with `isAsked(result)` before
1304
+ * reading the normal fields. `mandates.*` is unaffected: mandate management is always done as
1305
+ * yourself, never on someone else's behalf.
1306
+ */
1307
+ function actFor(principalId, opts) {
1308
+ return buildMethods(actingRequest(principalId, opts?.mandateId));
1309
+ }
1310
+ return { ...baseMethods, actFor };
187
1311
  }
188
1312
  //# sourceMappingURL=client.js.map