@profullstack/chat-plugins 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -103,3 +103,44 @@ link-local, CGNAT, multicast and reserved ranges, redirects re-checked hop by ho
103
103
  ## License
104
104
 
105
105
  MIT
106
+
107
+ ## Money plugins (0.2.0)
108
+
109
+ `FINANCE_CATALOG` lists Mercury (business banking), CoinPay (crypto payments)
110
+ and moomoo (brokerage and trading); `DEFAULT_PLUGINS` are the ones apps turn
111
+ on for every account (Mercury and CoinPay; each person signs in to their own
112
+ account). The confirmation gate goes in your tool-call layer:
113
+
114
+ ```js
115
+ import { applyPolicy, describeAction, policyFor, listTools } from "@profullstack/chat-plugins";
116
+
117
+ const policy = policyFor(plugin.url); // by server, not slug
118
+ const tools = applyPolicy(policy, await listTools(plugin), plugin.tradingMode ?? "paper");
119
+ // Only allowlisted reads run alone; every other tool (and any unknown name)
120
+ // is destructiveHint: true, so needsApproval() stops the loop for the person.
121
+ // describeAction(policy, tool, args) is the approval card: amount, currency,
122
+ // from, to, memo; or symbol, side, qty, type, prices, estimated cost, paper/live.
123
+ ```
124
+
125
+ moomoo in paper mode offers reads plus `sim_trade_*` orders only; live order
126
+ tools appear only in `"live"` mode, and still ask. `redactLog()` masks tokens,
127
+ long digit runs and amounts before anything reaches a log.
128
+
129
+ ## Docs plugins (0.3.0)
130
+
131
+ `DOCS_CATALOG` lists public, read-only documentation servers that need no
132
+ sign-in. It ships Microsoft Learn (`https://learn.microsoft.com/api/mcp`:
133
+ docs search, code sample search, page fetch), on by default.
134
+
135
+ `DEFAULT_PLUGINS` now holds every default: the money plugins, then the docs
136
+ plugins. A docs entry carries `auth: "none"`; seed it as ready to use, not as
137
+ "needs sign-in":
138
+
139
+ ```js
140
+ import { DEFAULT_PLUGINS, DOCS_CATALOG, mcpAddCommand } from "@profullstack/chat-plugins";
141
+
142
+ for (const d of DEFAULT_PLUGINS) seed(userId, d, d.auth === "none" ? "none" : "sign-in-on-first-use");
143
+
144
+ mcpAddCommand(DOCS_CATALOG[0]); // claude mcp add --transport http microsoft-learn https://learn.microsoft.com/api/mcp
145
+ mcpAddCommand(DOCS_CATALOG[0], "codex"); // codex mcp add microsoft-learn --url https://learn.microsoft.com/api/mcp
146
+ ```
package/index.d.ts CHANGED
@@ -317,3 +317,54 @@ export function fetchJson(
317
317
  export function parseWwwAuthenticate(header: string): Record<string, string>;
318
318
  export function protectedResourceCandidates(resource: URL): string[];
319
319
  export function authServerCandidates(issuer: string): string[];
320
+
321
+ // ── money plugins (src/money.js) ────────────────────────────────────────────
322
+
323
+ export type MoneyKind = "banking" | "crypto" | "trading";
324
+ export type TradingMode = "paper" | "live";
325
+ export interface PluginPolicy {
326
+ slug: string;
327
+ kind: MoneyKind;
328
+ /** Tools that only read. Exact names; anything else asks first. */
329
+ readOnly: ReadonlySet<string>;
330
+ /** OAuth scopes to ask for instead of everything the server offers. */
331
+ scopes?: string[];
332
+ /** Brokerage: tools that place, change or cancel PAPER orders. */
333
+ paperWrites?: ReadonlySet<string>;
334
+ }
335
+ export interface FinanceCatalogEntry {
336
+ slug: string;
337
+ name: string;
338
+ url: string;
339
+ description: string;
340
+ homepage: string;
341
+ icon: string;
342
+ /** On for every account (listed and switched on, not signed in). */
343
+ default: boolean;
344
+ /** "none": the server needs no sign-in, so a seeded row is ready to use. Absent: sign-in on first use. */
345
+ auth?: "none";
346
+ }
347
+ /** A public, read-only documentation server that needs no sign-in. */
348
+ export interface DocsCatalogEntry extends FinanceCatalogEntry {
349
+ auth: "none";
350
+ }
351
+ export interface ActionSummary {
352
+ title: string;
353
+ lines: { label: string; value: string }[];
354
+ account?: TradingMode;
355
+ note?: string;
356
+ }
357
+ export const MODEL_CAN_BE_WRONG: string;
358
+ export const FINANCE_CATALOG: readonly FinanceCatalogEntry[];
359
+ /** Everything on for every account: money plugins (sign-in on first use), then docs plugins (auth "none"). */
360
+ export const DEFAULT_PLUGINS: readonly FinanceCatalogEntry[];
361
+ export const DOCS_CATALOG: readonly DocsCatalogEntry[];
362
+ /** The one-line CLI command that registers an entry, e.g. `claude mcp add --transport http <slug> <url>`. */
363
+ export function mcpAddCommand(entry: { slug: string; url: string }, cli?: "claude" | "gemini" | "qwen" | "codex" | "opencode"): string;
364
+ export const POLICIES: Record<string, PluginPolicy>;
365
+ export function policyFor(url: string): PluginPolicy | null;
366
+ export function needsConfirmation(policy: PluginPolicy, tool: string): boolean;
367
+ export function visibleInMode(policy: PluginPolicy, tool: string, mode: TradingMode): boolean;
368
+ export function applyPolicy<T extends { name: string; annotations?: object }>(policy: PluginPolicy | null, tools: T[], mode?: TradingMode): T[];
369
+ export function describeAction(policy: PluginPolicy | null, tool: string, args: Record<string, unknown>): ActionSummary | null;
370
+ export function redactLog(v: unknown): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@profullstack/chat-plugins",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Chat plugins = remote MCP servers, with less hoops than connectors: paste a URL or pick from a catalog, sign-in is automatic (OAuth 2.1 + DCR + PKCE), and an agent loop runs the tools even on models with no native tool calling. Zero dependencies.",
6
6
  "keywords": [
package/src/docs.js ADDED
@@ -0,0 +1,43 @@
1
+ // Docs plugins: public, read-only documentation servers that need no sign-in.
2
+ // Entries with `default: true` are on for every account in apps that seed
3
+ // DEFAULT_PLUGINS (c0mpute chat, Infernet chat). `auth: "none"` tells the app
4
+ // to seed the row as ready to use, not as "needs sign-in".
5
+ //
6
+ // No Node imports: this also runs in the browser.
7
+
8
+ /** @type {readonly import("../index.js").DocsCatalogEntry[]} */
9
+ export const DOCS_CATALOG = Object.freeze([
10
+ Object.freeze({
11
+ slug: "microsoft-learn",
12
+ name: "Microsoft Learn (docs)",
13
+ url: "https://learn.microsoft.com/api/mcp",
14
+ description:
15
+ "Official Microsoft and Azure documentation in chat: search the docs, find code samples and read full pages as markdown. Read-only, no sign-in.",
16
+ homepage: "https://learn.microsoft.com",
17
+ icon: "https://learn.microsoft.com/favicon.ico",
18
+ default: true,
19
+ auth: "none",
20
+ }),
21
+ ]);
22
+
23
+ /**
24
+ * The one-line command that registers a catalog entry in a coding agent's CLI,
25
+ * e.g. `claude mcp add --transport http microsoft-learn https://learn.microsoft.com/api/mcp`.
26
+ * @param {{ slug: string, url: string }} entry
27
+ * @param {"claude" | "gemini" | "qwen" | "codex" | "opencode"} [cli]
28
+ */
29
+ export function mcpAddCommand(entry, cli = "claude") {
30
+ const slug = String(entry?.slug || "");
31
+ const url = String(entry?.url || "");
32
+ if (!/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) throw new Error("mcpAddCommand: bad slug");
33
+ let parsed;
34
+ try {
35
+ parsed = new URL(url);
36
+ } catch {
37
+ throw new Error("mcpAddCommand: bad url");
38
+ }
39
+ if (parsed.protocol !== "https:" || /[\s'"`$\;&|<>()]/.test(url)) throw new Error("mcpAddCommand: bad url");
40
+ if (cli === "codex" || cli === "opencode") return `${cli} mcp add ${slug} --url ${url}`;
41
+ if (cli === "claude" || cli === "gemini" || cli === "qwen") return `${cli} mcp add --transport http ${slug} ${url}`;
42
+ throw new Error(`mcpAddCommand: unknown cli ${cli}`);
43
+ }
package/src/index.js CHANGED
@@ -27,3 +27,16 @@ export { toOpenAITools, toolName, buildToolIndex, resolveTool, needsApproval, sl
27
27
  export { runToolLoop, iterateToolLoop, parseToolCall, normalizeReply, toolPrompt, wrapToolResult } from "./loop.js";
28
28
  export { CATALOG, makeCatalog, resolvePluginInput, uniqueSlug } from "./catalog.js";
29
29
  export { sealToken, openToken } from "./seal.js";
30
+ export {
31
+ MODEL_CAN_BE_WRONG,
32
+ FINANCE_CATALOG,
33
+ DEFAULT_PLUGINS,
34
+ POLICIES,
35
+ policyFor,
36
+ needsConfirmation,
37
+ visibleInMode,
38
+ applyPolicy,
39
+ describeAction,
40
+ redactLog,
41
+ } from "./money.js";
42
+ export { DOCS_CATALOG, mcpAddCommand } from "./docs.js";
package/src/money.js ADDED
@@ -0,0 +1,376 @@
1
+ // Money plugins: catalog entries for banking (Mercury), crypto payments
2
+ // (CoinPay) and brokerage (moomoo), which of them apps turn on by default,
3
+ // and the confirmation gate for their tools.
4
+ //
5
+ // The gate is meant for the app's tool-call layer, not a prompt: for a plugin
6
+ // with a policy, a tool may run on its own only when its exact name is on that
7
+ // plugin's read-only allowlist. applyPolicy() marks every other tool (a write,
8
+ // or a name never seen) destructiveHint: true before the tool loop sees it, so
9
+ // needsApproval() is true and the loop stops for the person. A server's own
10
+ // annotations cannot loosen it. Policies are chosen by server URL, not slug.
11
+ //
12
+ // Shared by c0mpute chat and Infernet chat so the two cannot drift. No Node
13
+ // imports: describeAction() also runs in the browser.
14
+
15
+ import { DOCS_CATALOG } from "./docs.js";
16
+
17
+ export const MODEL_CAN_BE_WRONG = "The model can be wrong. You decide: nothing here runs until you approve it.";
18
+ export const FINANCE_CATALOG = Object.freeze([
19
+ {
20
+ slug: "mercury",
21
+ name: "Mercury (business banking)",
22
+ url: "https://mcp.mercury.com/mcp",
23
+ description: "Your Mercury accounts in chat: balances, transactions, recipients, cards, statements and cash flow. Payment and transfer requests need your approval here and still go through Mercury's own approval. Sign in with your Mercury account.",
24
+ homepage: "https://mercury.com",
25
+ icon: "https://mercury.com/favicon.ico",
26
+ default: true
27
+ },
28
+ {
29
+ slug: "coinpay",
30
+ name: "CoinPay (crypto payments)",
31
+ url: "https://coinpayportal.com/api/mcp",
32
+ description: "Your CoinPay business in chat: crypto invoices, receivables aging, projects, contractors and pay runs. Creating anything needs your approval first. Sign in with your CoinPay account.",
33
+ homepage: "https://coinpayportal.com",
34
+ icon: "https://coinpayportal.com/favicon.ico",
35
+ default: true
36
+ },
37
+ {
38
+ slug: "moomoo",
39
+ name: "moomoo (brokerage and trading)",
40
+ url: "https://mcp.moomoo.com/mcp",
41
+ description: "Quotes, charts, screeners, news and your moomoo positions, balances and orders. Starts on paper trading; switching to live is your call, and every order needs your approval. The model can be wrong and you decide. Sign in with your moomoo account.",
42
+ homepage: "https://www.moomoo.com",
43
+ icon: "https://www.moomoo.com/favicon.ico",
44
+ default: false
45
+ }
46
+ ]);
47
+ // Everything apps switch on for every account: the money plugins each person
48
+ // signs in to, then the docs plugins that need no sign-in (auth: "none").
49
+ export const DEFAULT_PLUGINS = Object.freeze([...FINANCE_CATALOG.filter((e) => e.default), ...DOCS_CATALOG.filter((e) => e.default)]);
50
+ const MERCURY_READ = new Set([
51
+ "getCurrentDate",
52
+ "getAccount",
53
+ "getAccounts",
54
+ "getAccountCards",
55
+ "getAccountStatements",
56
+ "getTransaction",
57
+ "getTransactionById",
58
+ "listTransactions",
59
+ "getCashflowSummary",
60
+ "getAutoTransferRules",
61
+ "listCategories",
62
+ "listCredit",
63
+ "getCreditAccountStatements",
64
+ "getOrganization",
65
+ "getRecipient",
66
+ "getRecipients",
67
+ "getRecipientInvite",
68
+ "listRecipientInvites",
69
+ "listRecipientsAttachments",
70
+ "getTreasury",
71
+ "getTreasuryTransactions",
72
+ "getInvest",
73
+ "getInvestActivity",
74
+ "getCard",
75
+ "listCards",
76
+ "listMerchants",
77
+ "getUser",
78
+ "getUsers",
79
+ "getWebhook",
80
+ "getWebhooks",
81
+ "listSendMoneyApprovalRequests",
82
+ "getSendMoneyApprovalRequest",
83
+ "listTransferMoneyApprovalRequests",
84
+ "getTransferMoneyApprovalRequest",
85
+ "listTasks",
86
+ "getTask",
87
+ "getSafeRequest",
88
+ "getSafeRequests",
89
+ "getAttachment",
90
+ "getCustomer",
91
+ "listCustomers",
92
+ "listProducts",
93
+ "getInvoice",
94
+ "listInvoices",
95
+ "listInvoiceAttachments",
96
+ "listInvoicePayments",
97
+ "listBudgets",
98
+ "getBudget",
99
+ "getBudgetMembers",
100
+ "getBudgetExpenditures",
101
+ "listReceipts",
102
+ "getReceipt",
103
+ "listReimbursements",
104
+ "getReimbursement",
105
+ "getBooksInstances",
106
+ "getBooksSourceAccounts",
107
+ "getBooksTransactions",
108
+ "getBooksTransaction",
109
+ "getBooksLedgers",
110
+ "getBooksLedger",
111
+ "getBooksLedgerBalances",
112
+ "getBooksLineEntries",
113
+ "listBooksJournalEntries",
114
+ "retrieveBooksJournalEntry",
115
+ "getBooksTagGroups",
116
+ "getBooksTags",
117
+ "getBooksCategorizationRules",
118
+ "getBooksProfitAndLoss",
119
+ "getBooksBalanceSheet",
120
+ "getBooksCashFlow",
121
+ "getBooksBills",
122
+ "getBooksBill",
123
+ "getBooksInvoices",
124
+ "getBooksInvoice"
125
+ ]);
126
+ const COINPAY_READ = new Set([
127
+ "invoice_list",
128
+ "invoice_get",
129
+ "invoice_ar_aging",
130
+ "project_list",
131
+ "project_get",
132
+ "contractor_list",
133
+ "contractor_get",
134
+ "contractor_work_list",
135
+ "pay_run_list",
136
+ "pay_run_get",
137
+ "document_list",
138
+ "document_get"
139
+ ]);
140
+ const MOOMOO_READ = new Set([
141
+ "account_authorized_trd_accs",
142
+ "account_funds",
143
+ "account_positions",
144
+ "account_orders_active",
145
+ "account_orders_history",
146
+ "account_orders_detail",
147
+ "account_order_fills_today",
148
+ "account_fills_history",
149
+ "account_trading_info",
150
+ "sim_trade_account_list",
151
+ "sim_trade_cash_info",
152
+ "sim_trade_position_list",
153
+ "sim_trade_history_order_list",
154
+ "sim_trade_max_buy_sell",
155
+ "quote_market_snapshot",
156
+ "quote_market_state",
157
+ "quote_stock_quote",
158
+ "quote_stock_feed",
159
+ "quote_stock_basicinfo",
160
+ "quote_stock_screen",
161
+ "quote_option_screen",
162
+ "quote_warrant_screen",
163
+ "quote_rt_ticker",
164
+ "quote_rt_data",
165
+ "quote_order_book",
166
+ "quote_cur_kline",
167
+ "quote_history_kline",
168
+ "quote_trading_days",
169
+ "quote_top_ten_brokers",
170
+ "quote_capital_flow",
171
+ "quote_capital_flow_history",
172
+ "quote_capital_distribution",
173
+ "quote_plate_list",
174
+ "quote_plate_stock",
175
+ "quote_owner_plate",
176
+ "quote_referencefuture_list",
177
+ "quote_future_info",
178
+ "quote_option_chain",
179
+ "quote_option_expiration_date",
180
+ "quote_option_volatility",
181
+ "quote_option_exercise_probability",
182
+ "quote_user_security",
183
+ "quote_user_security_group",
184
+ "quote_valuation_detail",
185
+ "quote_valuation_plate_stock_list",
186
+ "quote_valuation_index_stock_plate_list",
187
+ "quote_valuation_index_component_stock_list",
188
+ "quote_financials_statements",
189
+ "quote_financials_revenue_breakdown",
190
+ "quote_financials_earnings_price_history",
191
+ "quote_company_profile",
192
+ "quote_company_executives",
193
+ "quote_company_executive_background",
194
+ "quote_company_operational_efficiency",
195
+ "quote_corporate_actions_dividends",
196
+ "quote_corporate_actions_stock_splits",
197
+ "quote_corporate_actions_buybacks",
198
+ "quote_corporate_actions_rehab",
199
+ "quote_shareholders_overview",
200
+ "quote_shareholders_institutional",
201
+ "quote_shareholders_holding_changes",
202
+ "quote_shareholders_holder_detail",
203
+ "quote_insider_trade_list",
204
+ "quote_insider_holder_list",
205
+ "quote_short_interest",
206
+ "quote_daily_short_volume",
207
+ "quote_research_rating_summary",
208
+ "quote_research_analyst_consensus",
209
+ "quote_research_morningstar_report",
210
+ "quote_news_search",
211
+ "quote_community_search",
212
+ "quote_economic_calendar_search",
213
+ "quote_economic_calendar_hot",
214
+ "quote_ipo_list_us",
215
+ "quote_ipo_list_hk",
216
+ "quote_ipo_list_cn",
217
+ "quote_ipo_list_sg",
218
+ "quote_ipo_list_my"
219
+ ]);
220
+ const MOOMOO_PAPER_WRITES = new Set(["sim_trade_input_order", "sim_trade_modify_order", "sim_trade_cancel_order"]);
221
+ export const POLICIES = {
222
+ mercury: {
223
+ slug: "mercury",
224
+ kind: "banking",
225
+ readOnly: MERCURY_READ,
226
+ scopes: ["read", "offline_access", "transactions:request", "transfers:request"]
227
+ },
228
+ coinpay: { slug: "coinpay", kind: "crypto", readOnly: COINPAY_READ },
229
+ moomoo: { slug: "moomoo", kind: "trading", readOnly: MOOMOO_READ, paperWrites: MOOMOO_PAPER_WRITES }
230
+ };
231
+ function parse(u) {
232
+ try {
233
+ return new URL(u);
234
+ } catch {
235
+ return null;
236
+ }
237
+ }
238
+ export function policyFor(url) {
239
+ const u = parse(url);
240
+ if (!u)
241
+ return null;
242
+ const host = u.hostname.toLowerCase().replace(/\.$/, "");
243
+ if (host === "mcp.mercury.com")
244
+ return POLICIES.mercury;
245
+ if (host === "mcp.moomoo.com")
246
+ return POLICIES.moomoo;
247
+ if (host === "coinpayportal.com" || host === "www.coinpayportal.com")
248
+ return POLICIES.coinpay;
249
+ return null;
250
+ }
251
+ export function needsConfirmation(policy, tool) {
252
+ return !policy.readOnly.has(tool);
253
+ }
254
+ export function visibleInMode(policy, tool, mode) {
255
+ if (policy.kind !== "trading" || mode === "live")
256
+ return true;
257
+ return policy.readOnly.has(tool) || !!policy.paperWrites?.has(tool);
258
+ }
259
+ export function applyPolicy(policy, tools, mode = "paper") {
260
+ if (!policy)
261
+ return tools;
262
+ return tools.filter((t) => visibleInMode(policy, t.name, mode)).map((t) => needsConfirmation(policy, t.name) ? { ...t, annotations: { ...t.annotations ?? {}, readOnlyHint: false, destructiveHint: true } } : { ...t, annotations: { ...t.annotations ?? {}, readOnlyHint: true, destructiveHint: false } });
263
+ }
264
+ const str = (v) => v === undefined || v === null ? "" : typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : JSON.stringify(v);
265
+ function pick(args, names) {
266
+ const norm = (k) => k.toLowerCase().replace(/[_-]/g, "");
267
+ const want = names.map(norm);
268
+ const scan = (o) => {
269
+ for (const w of want) {
270
+ for (const [k, v] of Object.entries(o))
271
+ if (norm(k) === w && v !== undefined && v !== null && v !== "")
272
+ return str(v);
273
+ }
274
+ return "";
275
+ };
276
+ const top = scan(args);
277
+ if (top)
278
+ return top;
279
+ for (const v of Object.values(args)) {
280
+ if (v && typeof v === "object" && !Array.isArray(v)) {
281
+ const inner = scan(v);
282
+ if (inner)
283
+ return inner;
284
+ }
285
+ }
286
+ return "";
287
+ }
288
+ function humanTool(tool) {
289
+ const s = tool.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/_/g, " ").toLowerCase();
290
+ return s.charAt(0).toUpperCase() + s.slice(1);
291
+ }
292
+ const num = (s) => {
293
+ if (!s)
294
+ return null;
295
+ const n = Number(String(s).replace(/,/g, ""));
296
+ return Number.isFinite(n) ? n : null;
297
+ };
298
+ function tradingSummary(tool, args) {
299
+ const paper = tool.startsWith("sim_trade_");
300
+ const lines = [];
301
+ const add = (label, value) => {
302
+ if (value)
303
+ lines.push({ label, value });
304
+ };
305
+ const isCancel = /cancel/.test(tool);
306
+ const isChange = /modify|replace/.test(tool);
307
+ const isPlace = !isCancel && !isChange && /order|place|confirm/.test(tool);
308
+ const title = isCancel ? "Cancel order" : isChange ? "Change order" : /confirm/.test(tool) ? "Confirm order" : isPlace ? "Place order" : humanTool(tool);
309
+ add("Symbol", pick(args, ["code", "symbol", "ticker", "security"]));
310
+ add("Side", pick(args, ["side", "trd_side", "direction"]));
311
+ const qty = pick(args, ["qty", "quantity", "new_qty", "shares"]);
312
+ add("Quantity", qty);
313
+ const type = pick(args, ["order_type", "type"]);
314
+ add("Order type", type);
315
+ const price = pick(args, ["price", "limit_price", "new_price"]);
316
+ add("Limit price", price);
317
+ add("Stop / trigger price", pick(args, ["aux_price", "stop_price", "trigger_price"]));
318
+ add("Time in force", pick(args, ["time_in_force", "tif"]));
319
+ add("Order id", pick(args, ["order_id", "confirm_id"]));
320
+ if (isPlace || isChange) {
321
+ const q = num(qty);
322
+ const p = num(price);
323
+ lines.push({
324
+ label: "Estimated cost",
325
+ value: q !== null && p !== null && !/MARKET/i.test(type) ? `${(q * p).toLocaleString("en-US", { maximumFractionDigits: 4 })} (quantity x price, before fees; options and futures also multiply by the contract size)` : "at the market price, not known until it fills"
326
+ });
327
+ }
328
+ add("Account id", pick(args, ["acc_id", "account_id"]));
329
+ lines.push({ label: "Account", value: paper ? "PAPER (simulated, no real money)" : "LIVE (real money)" });
330
+ return { title, lines, account: paper ? "paper" : "live", note: MODEL_CAN_BE_WRONG };
331
+ }
332
+ function moneySummary(kind, tool, args) {
333
+ const lines = [];
334
+ const add = (label, value) => {
335
+ if (value)
336
+ lines.push({ label, value });
337
+ };
338
+ let amount = pick(args, ["amount", "amountUsd", "value", "total", "paymentAmount"]);
339
+ let currency = pick(args, ["currency", "currencyCode", "asset", "coin"]);
340
+ const items = Array.isArray(args.lineItems) ? args.lineItems : null;
341
+ if (!amount && items) {
342
+ const t = items.reduce((s, i) => s + (Number(i?.quantity) || 0) * (Number(i?.unit_price) || 0), 0);
343
+ amount = `${t.toLocaleString("en-US", { maximumFractionDigits: 8 })} before tax and discount (${items.length} line item${items.length === 1 ? "" : "s"})`;
344
+ if (!currency)
345
+ currency = "USD";
346
+ }
347
+ if (typeof args.minutes === "number")
348
+ add("Time", `${args.minutes} minutes`);
349
+ add("Amount", amount);
350
+ add("Currency", currency);
351
+ add("From", pick(args, ["fromAccountId", "sourceAccountId", "from", "accountId", "fromAccount", "businessId", "fromWallet"]));
352
+ add("To", pick(args, ["recipientId", "toAccountId", "destinationAccountId", "to", "recipient", "toAddress", "address", "clientId", "contractorId", "projectId"]));
353
+ add("Memo", pick(args, ["memo", "note", "notes", "externalMemo", "description", "purpose", "remark"]));
354
+ add("Payment method", pick(args, ["paymentMethod", "method", "network", "chain"]));
355
+ return {
356
+ title: humanTool(tool),
357
+ lines,
358
+ note: kind === "banking" ? "Mercury payment and transfer requests still need an approver in Mercury." : MODEL_CAN_BE_WRONG
359
+ };
360
+ }
361
+ export function describeAction(policy, tool, args) {
362
+ if (!policy)
363
+ return null;
364
+ const a = args && typeof args === "object" ? args : {};
365
+ return policy.kind === "trading" ? tradingSummary(tool, a) : moneySummary(policy.kind, tool, a);
366
+ }
367
+ export function redactLog(v) {
368
+ const s = v instanceof Error ? `${v.name}: ${v.message}` : typeof v === "string" ? v : (() => {
369
+ try {
370
+ return JSON.stringify(v);
371
+ } catch {
372
+ return String(v);
373
+ }
374
+ })();
375
+ return s.replace(/(bearer\s+)\S+/gi, "$1[redacted]").replace(/("?(?:access_token|refresh_token|id_token|client_secret|code|code_verifier|token|password|secret)"?\s*[:=]\s*"?)[^"&\s,}]+/gi, "$1[redacted]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g, "[jwt]").replace(/[A-Za-z0-9_\-+/=]{32,}/g, "[opaque]").replace(/\d[\d -]{6,}\d/g, "[number]").replace(/[$€£]\s?\d[\d,]*(\.\d+)?/g, "[amount]").slice(0, 500);
376
+ }