@ergoblockchain/sage-widget 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/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import { useState, useRef, useEffect } from 'react';
1
+ import { useState, useRef, useEffect, useMemo } from 'react';
2
2
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
3
3
 
4
4
  // src/react/SageActivityFeed.tsx
@@ -12,13 +12,151 @@ var DEFAULT_REFRESH_MS = 6e4;
12
12
  async function fetchSageActivity(opts = {}) {
13
13
  const base = opts.apiBase ?? DEFAULT_API_BASE;
14
14
  const limit = Math.min(Math.max(opts.limit ?? DEFAULT_LIMIT, 1), 25);
15
- const url = `${base}/api/sage/activity?limit=${limit}`;
15
+ const url = `${trimSlash(base)}/api/sage/activity?limit=${limit}`;
16
16
  const res = await fetch(url, { signal: opts.signal });
17
17
  if (!res.ok) {
18
18
  throw new Error(`sage activity ${res.status}`);
19
19
  }
20
20
  return await res.json();
21
21
  }
22
+ async function fetchSageQuote(opts) {
23
+ const res = await fetch(`${apiBase(opts)}/api/sage/quote`, {
24
+ method: "POST",
25
+ headers: jsonHeaders(opts),
26
+ body: JSON.stringify({
27
+ question: opts.question,
28
+ history: opts.history ?? []
29
+ }),
30
+ signal: opts.signal
31
+ });
32
+ const body = await parseJson(res);
33
+ if (!res.ok) throw new Error(readError(body, `sage quote ${res.status}`));
34
+ return body;
35
+ }
36
+ async function verifySagePayment(opts) {
37
+ const res = await fetch(`${apiBase(opts)}/api/sage/verify-payment`, {
38
+ method: "POST",
39
+ headers: jsonHeaders(opts),
40
+ body: JSON.stringify({
41
+ quote: opts.quote,
42
+ question: opts.question,
43
+ noteBoxId: opts.noteBoxId
44
+ }),
45
+ signal: opts.signal
46
+ });
47
+ const body = await parseJson(res);
48
+ if (!res.ok) throw new Error(readError(body, `sage verify-payment ${res.status}`));
49
+ return body;
50
+ }
51
+ async function fetchSageReceipt(id, opts = {}) {
52
+ const res = await fetch(`${apiBase(opts)}/api/sage/receipt/${encodeURIComponent(id)}`, {
53
+ headers: requestHeaders(opts),
54
+ signal: opts.signal
55
+ });
56
+ const body = await parseJson(res);
57
+ if (!res.ok) throw new Error(readError(body, `sage receipt ${res.status}`));
58
+ return body;
59
+ }
60
+ function createSagePaymentIntent(opts) {
61
+ const base = trimSlash(opts.apiBase ?? DEFAULT_API_BASE);
62
+ return {
63
+ type: "sage.payment_intent.v1",
64
+ network: opts.network ?? "ergo-testnet",
65
+ createdAt: opts.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
66
+ question: opts.question,
67
+ ...opts.tenant?.id || opts.tenant?.label ? { tenant: { id: opts.tenant.id, label: opts.tenant.label } } : {},
68
+ quote: opts.quote,
69
+ amountErg: opts.quote.price,
70
+ receiverAddress: opts.quote.receiverAddress,
71
+ reserveBoxId: opts.quote.reserveBoxId,
72
+ taskHash: opts.quote.taskHash,
73
+ expiresAt: opts.quote.expiresAt,
74
+ deadline: opts.quote.deadline,
75
+ verifyEndpoint: `${base}/api/sage/verify-payment`,
76
+ receiptEndpointTemplate: `${base}/api/sage/receipt/{receiptId}`
77
+ };
78
+ }
79
+ function serializeSagePaymentIntent(intent) {
80
+ return JSON.stringify(intent, null, 2);
81
+ }
82
+ async function streamSageChat(opts) {
83
+ const res = await fetch(`${apiBase(opts)}/api/sage/chat`, {
84
+ method: "POST",
85
+ headers: jsonHeaders(opts),
86
+ body: JSON.stringify({
87
+ messages: opts.messages,
88
+ ...opts.paymentToken ? { paymentToken: opts.paymentToken } : {}
89
+ }),
90
+ signal: opts.signal
91
+ });
92
+ if (res.status === 402) {
93
+ const body = await parseJson(res);
94
+ return {
95
+ ok: false,
96
+ status: res.status,
97
+ text: "",
98
+ paymentRequired: body
99
+ };
100
+ }
101
+ if (!res.ok) {
102
+ const body = await parseJson(res);
103
+ return {
104
+ ok: false,
105
+ status: res.status,
106
+ text: "",
107
+ error: readError(body, `sage chat ${res.status}`)
108
+ };
109
+ }
110
+ if (!res.body) {
111
+ return { ok: false, status: res.status, text: "", error: "Sage chat stream missing body" };
112
+ }
113
+ const reader = res.body.getReader();
114
+ const decoder = new TextDecoder();
115
+ let buffer = "";
116
+ let text = "";
117
+ let tier;
118
+ while (true) {
119
+ const { value, done } = await reader.read();
120
+ if (done) break;
121
+ buffer += decoder.decode(value, { stream: true });
122
+ const parts = buffer.split("\n\n");
123
+ buffer = parts.pop() ?? "";
124
+ for (const part of parts) {
125
+ const event = parseSseEvent(part);
126
+ if (!event) continue;
127
+ if (event.type === "delta") text += event.text;
128
+ if (event.type === "tier") tier = event.tier;
129
+ opts.onEvent?.(event);
130
+ if (event.type === "error") {
131
+ return {
132
+ ok: false,
133
+ status: res.status,
134
+ text,
135
+ tier,
136
+ error: event.message
137
+ };
138
+ }
139
+ }
140
+ }
141
+ if (buffer.trim()) {
142
+ const event = parseSseEvent(buffer);
143
+ if (event) {
144
+ if (event.type === "delta") text += event.text;
145
+ if (event.type === "tier") tier = event.tier;
146
+ opts.onEvent?.(event);
147
+ if (event.type === "error") {
148
+ return {
149
+ ok: false,
150
+ status: res.status,
151
+ text,
152
+ tier,
153
+ error: event.message
154
+ };
155
+ }
156
+ }
157
+ }
158
+ return { ok: true, status: res.status, text, tier };
159
+ }
22
160
  function nanoToErg(nano) {
23
161
  if (!nano || nano <= 0) return "0";
24
162
  const erg = nano / 1e9;
@@ -35,16 +173,92 @@ function relativeTime(ms, now = Date.now()) {
35
173
  const day = Math.floor(hr / 24);
36
174
  return `${day}d ago`;
37
175
  }
38
- function receiptUrl(txId, apiBase = DEFAULT_API_BASE) {
39
- return `${apiBase}/r/sage/${txId}`;
176
+ function receiptUrl(txId, apiBase2 = DEFAULT_API_BASE) {
177
+ return `${trimSlash(apiBase2)}/r/sage/${txId}`;
40
178
  }
41
179
  function explorerUrl(txId, network = "testnet") {
42
180
  return network === "testnet" ? `https://testnet.ergoplatform.com/transactions/${txId}` : `https://explorer.ergoplatform.com/transactions/${txId}`;
43
181
  }
182
+ function apiBase(opts) {
183
+ return trimSlash(opts.apiBase ?? DEFAULT_API_BASE);
184
+ }
185
+ function trimSlash(value) {
186
+ return value.replace(/\/+$/, "");
187
+ }
188
+ function requestHeaders(opts) {
189
+ return {
190
+ ...opts.tenant?.id ? { "x-sage-tenant-id": opts.tenant.id } : {},
191
+ ...opts.tenant?.headers ?? {},
192
+ ...opts.headers ?? {}
193
+ };
194
+ }
195
+ function jsonHeaders(opts) {
196
+ return {
197
+ "content-type": "application/json",
198
+ ...requestHeaders(opts)
199
+ };
200
+ }
201
+ async function parseJson(res) {
202
+ const text = await res.text();
203
+ if (!text) return null;
204
+ try {
205
+ return JSON.parse(text);
206
+ } catch {
207
+ return { error: text };
208
+ }
209
+ }
210
+ function readError(body, fallback) {
211
+ if (body && typeof body === "object" && "error" in body) {
212
+ const error = body.error;
213
+ if (typeof error === "string") return error;
214
+ }
215
+ return fallback;
216
+ }
217
+ function parseSseEvent(raw) {
218
+ let eventName = "message";
219
+ let data = "";
220
+ for (const line of raw.split("\n")) {
221
+ if (line.startsWith("event:")) eventName = line.slice("event:".length).trim();
222
+ if (line.startsWith("data:")) data += line.slice("data:".length).trim();
223
+ }
224
+ if (!data) return null;
225
+ let parsed;
226
+ try {
227
+ parsed = JSON.parse(data);
228
+ } catch {
229
+ return null;
230
+ }
231
+ if (eventName === "tier") {
232
+ const tier = parsed.tier === "premium" ? "premium" : "free";
233
+ return {
234
+ type: "tier",
235
+ tier,
236
+ ...typeof parsed.model === "string" ? { model: parsed.model } : {}
237
+ };
238
+ }
239
+ if (eventName === "delta" && typeof parsed.text === "string") {
240
+ return { type: "delta", text: parsed.text };
241
+ }
242
+ if (eventName === "done") {
243
+ return {
244
+ type: "done",
245
+ ...typeof parsed.stopReason === "string" ? { stopReason: parsed.stopReason } : {},
246
+ ...typeof parsed.inputTokens === "number" ? { inputTokens: parsed.inputTokens } : {},
247
+ ...typeof parsed.outputTokens === "number" ? { outputTokens: parsed.outputTokens } : {}
248
+ };
249
+ }
250
+ if (eventName === "error") {
251
+ return {
252
+ type: "error",
253
+ message: typeof parsed.message === "string" ? parsed.message : "Sage stream error"
254
+ };
255
+ }
256
+ return null;
257
+ }
44
258
  var ONE_MIN = 6e4;
45
259
  function SageActivityFeed(props) {
46
260
  const {
47
- apiBase,
261
+ apiBase: apiBase2,
48
262
  limit = DEFAULT_LIMIT,
49
263
  refreshMs = DEFAULT_REFRESH_MS,
50
264
  onUpdate,
@@ -71,7 +285,7 @@ function SageActivityFeed(props) {
71
285
  async function load() {
72
286
  try {
73
287
  const data = await fetchSageActivity({
74
- apiBase,
288
+ apiBase: apiBase2,
75
289
  limit,
76
290
  signal: abort.signal
77
291
  });
@@ -96,7 +310,7 @@ function SageActivityFeed(props) {
96
310
  if (pollId) clearInterval(pollId);
97
311
  clearInterval(tickId);
98
312
  };
99
- }, [apiBase, limit, refreshMs]);
313
+ }, [apiBase2, limit, refreshMs]);
100
314
  if (children) {
101
315
  return /* @__PURE__ */ jsx(Fragment, { children: children({ loading, response, error }) });
102
316
  }
@@ -108,7 +322,7 @@ function SageActivityFeed(props) {
108
322
  loading,
109
323
  events: response?.events ?? [],
110
324
  network: response?.network ?? "testnet",
111
- apiBase,
325
+ apiBase: apiBase2,
112
326
  now
113
327
  }
114
328
  ),
@@ -138,22 +352,22 @@ function List({
138
352
  loading,
139
353
  events,
140
354
  network,
141
- apiBase,
355
+ apiBase: apiBase2,
142
356
  now
143
357
  }) {
144
358
  if (loading) return /* @__PURE__ */ jsx("div", { style: emptyStyle, children: "Loading\u2026" });
145
359
  if (events.length === 0)
146
360
  return /* @__PURE__ */ jsx("div", { style: emptyStyle, children: "No activity yet \u2014 be the first to ask Sage a paid query." });
147
- return /* @__PURE__ */ jsx("div", { children: events.map((evt) => /* @__PURE__ */ jsx(Row, { evt, network, apiBase, now }, evt.txId)) });
361
+ return /* @__PURE__ */ jsx("div", { children: events.map((evt) => /* @__PURE__ */ jsx(Row, { evt, network, apiBase: apiBase2, now }, evt.txId)) });
148
362
  }
149
363
  function Row({
150
364
  evt,
151
365
  network,
152
- apiBase,
366
+ apiBase: apiBase2,
153
367
  now
154
368
  }) {
155
369
  const isSettle = evt.type === "settlement";
156
- const href = isSettle ? receiptUrl(evt.txId, apiBase) : explorerUrl(evt.txId, network);
370
+ const href = isSettle ? receiptUrl(evt.txId, apiBase2) : explorerUrl(evt.txId, network);
157
371
  const amount = isSettle ? evt.paymentNanoErg ?? evt.inflowNanoErg : evt.inflowNanoErg;
158
372
  const chipStyle = isSettle ? chipSettleStyle : chipIssueStyle;
159
373
  const chipText = isSettle ? "Settled" : evt.type === "issuance" ? "Issued" : "Transfer";
@@ -291,7 +505,575 @@ var errorStyle = {
291
505
  ...emptyStyle,
292
506
  color: "#f87171"
293
507
  };
508
+ function SagePaymentWidget(props) {
509
+ const {
510
+ apiBase: apiBase2 = DEFAULT_API_BASE,
511
+ tenant,
512
+ initialMessages = [],
513
+ placeholder = "Ask Sage about Ergo or agent payments...",
514
+ paymentInstructions,
515
+ showPaymentIntent = true,
516
+ testnetWarning = "Testnet proof flow. The widget never signs funds; connect your own reviewed wallet layer before handling real value.",
517
+ className,
518
+ style,
519
+ title = "Ask Sage"
520
+ } = props;
521
+ const [messages, setMessages] = useState(initialMessages);
522
+ const [input, setInput] = useState("");
523
+ const [phase, setPhase] = useState("idle");
524
+ const [quoteResponse, setQuoteResponse] = useState(null);
525
+ const [paymentIntent, setPaymentIntent] = useState(null);
526
+ const [activeQuestion, setActiveQuestion] = useState("");
527
+ const [noteBoxId, setNoteBoxId] = useState("");
528
+ const [receipt, setReceipt] = useState(null);
529
+ const [receiptBundle, setReceiptBundle] = useState(null);
530
+ const [error, setError] = useState(null);
531
+ const [tier, setTier] = useState(null);
532
+ const mountedRef = useRef(true);
533
+ useEffect(() => {
534
+ mountedRef.current = true;
535
+ return () => {
536
+ mountedRef.current = false;
537
+ };
538
+ }, []);
539
+ const busy = phase === "quoting" || phase === "verifying" || phase === "streaming";
540
+ const apiOpts = useMemo(() => ({ apiBase: apiBase2, tenant }), [apiBase2, tenant]);
541
+ async function submit(e) {
542
+ e.preventDefault();
543
+ const question = input.trim();
544
+ if (!question || busy) return;
545
+ const userMessage = { role: "user", content: question };
546
+ const nextMessages = [...messages, userMessage];
547
+ setMessages(nextMessages);
548
+ props.onMessage?.(userMessage, nextMessages);
549
+ setInput("");
550
+ setError(null);
551
+ setReceipt(null);
552
+ setReceiptBundle(null);
553
+ setQuoteResponse(null);
554
+ setPaymentIntent(null);
555
+ setActiveQuestion(question);
556
+ setNoteBoxId("");
557
+ setTier(null);
558
+ transition("quoting");
559
+ try {
560
+ const quote2 = await fetchSageQuote({
561
+ ...apiOpts,
562
+ question,
563
+ history: messages
564
+ });
565
+ props.onQuote?.(quote2);
566
+ if (quote2.premium) {
567
+ if (!quote2.quote) throw new Error("Sage marked this question premium but did not return a quote.");
568
+ const intent = createSagePaymentIntent({
569
+ ...apiOpts,
570
+ question,
571
+ quote: quote2.quote
572
+ });
573
+ setPaymentIntent(intent);
574
+ setQuoteResponse(quote2);
575
+ props.onPaymentIntent?.(intent);
576
+ transition("payment_required", { quote: quote2.quote, paymentIntent: intent });
577
+ return;
578
+ }
579
+ await streamAnswer(nextMessages, void 0, question);
580
+ } catch (err) {
581
+ fail(err);
582
+ }
583
+ }
584
+ async function verifyAndContinue() {
585
+ const quote2 = quoteResponse?.quote;
586
+ const note = noteBoxId.trim();
587
+ if (!quote2 || !activeQuestion || !note || busy) return;
588
+ setError(null);
589
+ transition("verifying");
590
+ let verified;
591
+ try {
592
+ verified = await verifySagePayment({
593
+ ...apiOpts,
594
+ quote: quote2,
595
+ question: activeQuestion,
596
+ noteBoxId: note
597
+ });
598
+ } catch (err) {
599
+ transition("payment_required");
600
+ fail(err, false);
601
+ return;
602
+ }
603
+ if (!mountedRef.current) return;
604
+ setReceipt(verified);
605
+ props.onReceipt?.(verified);
606
+ setQuoteResponse(null);
607
+ setPaymentIntent(null);
608
+ setNoteBoxId("");
609
+ transition("streaming", { quote: null, paymentIntent: null, receipt: verified });
610
+ try {
611
+ const bundle = await fetchSageReceipt(verified.receiptId, apiOpts);
612
+ if (!mountedRef.current) return;
613
+ setReceiptBundle(bundle);
614
+ props.onReceiptBundle?.(bundle);
615
+ emitStatus("streaming", { quote: null, paymentIntent: null, receipt: verified, receiptBundle: bundle });
616
+ } catch (bundleErr) {
617
+ props.onError?.(bundleErr);
618
+ }
619
+ try {
620
+ await streamAnswer(messages, verified.paymentToken, activeQuestion);
621
+ } catch (err) {
622
+ fail(err);
623
+ }
624
+ }
625
+ async function streamAnswer(baseMessages, paymentToken, fallbackQuestion) {
626
+ transition("streaming");
627
+ let text = "";
628
+ const placeholderMessage = { role: "assistant", content: "" };
629
+ setMessages([...baseMessages, placeholderMessage]);
630
+ const result = await streamSageChat({
631
+ ...apiOpts,
632
+ messages: baseMessages,
633
+ paymentToken,
634
+ onEvent(event) {
635
+ if (!mountedRef.current) return;
636
+ if (event.type === "tier") {
637
+ setTier(event.tier);
638
+ props.onTier?.(event.tier);
639
+ emitStatus("streaming", { tier: event.tier, messages: baseMessages });
640
+ }
641
+ if (event.type === "delta") {
642
+ text += event.text;
643
+ setMessages([...baseMessages, { role: "assistant", content: text }]);
644
+ }
645
+ }
646
+ });
647
+ if (!result.ok) {
648
+ if (result.paymentRequired) {
649
+ const question = fallbackQuestion ?? lastUserQuestion(baseMessages) ?? activeQuestion;
650
+ const quote2 = await fetchSageQuote({
651
+ ...apiOpts,
652
+ question,
653
+ history: baseMessages.slice(0, -1)
654
+ });
655
+ if (!mountedRef.current) return;
656
+ props.onQuote?.(quote2);
657
+ setQuoteResponse(quote2);
658
+ setActiveQuestion(question);
659
+ const intent = quote2.quote ? createSagePaymentIntent({ ...apiOpts, question, quote: quote2.quote }) : null;
660
+ setPaymentIntent(intent);
661
+ if (intent) props.onPaymentIntent?.(intent);
662
+ transition("payment_required", { quote: quote2.quote ?? null, paymentIntent: intent });
663
+ return;
664
+ }
665
+ throw new Error(result.error ?? "Sage chat failed.");
666
+ }
667
+ if (!mountedRef.current) return;
668
+ if (result.text && result.text !== text) {
669
+ setMessages([...baseMessages, { role: "assistant", content: result.text }]);
670
+ }
671
+ transition("idle");
672
+ }
673
+ function fail(err, setErrorPhase = true) {
674
+ const message = err instanceof Error ? err.message : "Sage request failed.";
675
+ setError(message);
676
+ if (setErrorPhase) transition("error", { error: message });
677
+ else emitStatus(phase, { error: message });
678
+ props.onError?.(err);
679
+ }
680
+ function transition(next, overrides = {}) {
681
+ setPhase(next);
682
+ props.onPhase?.(next);
683
+ emitStatus(next, overrides);
684
+ }
685
+ function emitStatus(nextPhase, overrides = {}) {
686
+ const has = (key) => Object.prototype.hasOwnProperty.call(overrides, key);
687
+ props.onStatus?.({
688
+ phase: nextPhase,
689
+ tier: has("tier") ? overrides.tier ?? null : tier,
690
+ quote: has("quote") ? overrides.quote ?? null : quoteResponse?.quote ?? null,
691
+ paymentIntent: has("paymentIntent") ? overrides.paymentIntent ?? null : paymentIntent,
692
+ receipt: has("receipt") ? overrides.receipt ?? null : receipt,
693
+ receiptBundle: has("receiptBundle") ? overrides.receiptBundle ?? null : receiptBundle,
694
+ error: has("error") ? overrides.error ?? null : error,
695
+ messages: overrides.messages ?? messages,
696
+ activeQuestion: has("activeQuestion") ? overrides.activeQuestion ?? null : activeQuestion || null
697
+ });
698
+ }
699
+ const quote = quoteResponse?.quote;
700
+ const showPaymentPanel = quote && !receipt;
701
+ async function copyPaymentIntent() {
702
+ if (!paymentIntent) return;
703
+ await copyText(serializeSagePaymentIntent(paymentIntent));
704
+ }
705
+ async function launchWallet() {
706
+ if (!paymentIntent || !props.walletLauncher || busy) return;
707
+ setError(null);
708
+ try {
709
+ const result = await props.walletLauncher(paymentIntent);
710
+ if (result?.ok === false) {
711
+ throw new Error(result.error ?? "Wallet flow did not produce a Note.");
712
+ }
713
+ if (result?.noteBoxId) setNoteBoxId(result.noteBoxId);
714
+ } catch (err) {
715
+ fail(err, false);
716
+ }
717
+ }
718
+ return /* @__PURE__ */ jsxs("section", { className, style: { ...rootStyle2, ...style }, children: [
719
+ /* @__PURE__ */ jsxs("header", { style: headerStyle2, children: [
720
+ /* @__PURE__ */ jsxs("div", { children: [
721
+ /* @__PURE__ */ jsx("div", { style: eyebrowStyle, children: tenant?.label ?? "Ergo agent economy" }),
722
+ /* @__PURE__ */ jsx("h2", { style: titleStyle, children: title })
723
+ ] }),
724
+ /* @__PURE__ */ jsx("span", { style: badgeStyle, children: tier ? tier.toUpperCase() : "SAGE" })
725
+ ] }),
726
+ /* @__PURE__ */ jsx("div", { style: messagesStyle, "aria-live": "polite", children: messages.length === 0 ? /* @__PURE__ */ jsx("div", { style: emptyStyle2, children: "Free questions answer immediately. Premium questions return an Accord Note quote." }) : messages.map((message, index) => /* @__PURE__ */ jsx(
727
+ "div",
728
+ {
729
+ style: message.role === "user" ? userBubbleStyle : assistantBubbleStyle,
730
+ children: message.content || (message.role === "assistant" && phase === "streaming" ? "Thinking..." : "")
731
+ },
732
+ `${message.role}-${index}`
733
+ )) }),
734
+ showPaymentPanel ? /* @__PURE__ */ jsxs("div", { style: paymentStyle, children: [
735
+ /* @__PURE__ */ jsxs("div", { style: paymentHeaderStyle, children: [
736
+ /* @__PURE__ */ jsx("strong", { children: "Payment required" }),
737
+ /* @__PURE__ */ jsxs("span", { children: [
738
+ quote.price,
739
+ " ERG testnet"
740
+ ] })
741
+ ] }),
742
+ /* @__PURE__ */ jsxs("p", { style: helperStyle, children: [
743
+ paymentInstructions?.helperText ?? "Issue an Ergo testnet Note for this quote, then paste the created Note box id.",
744
+ paymentInstructions?.walletUrl ? /* @__PURE__ */ jsxs(Fragment, { children: [
745
+ " ",
746
+ /* @__PURE__ */ jsx("a", { href: paymentInstructions.walletUrl, target: "_blank", rel: "noopener noreferrer", style: inlineLinkStyle, children: "Wallet guide" })
747
+ ] }) : null
748
+ ] }),
749
+ /* @__PURE__ */ jsx(Field, { label: "Quote", value: quote.quoteId }),
750
+ /* @__PURE__ */ jsx(Field, { label: "Receiver", value: quote.receiverAddress, copy: true }),
751
+ /* @__PURE__ */ jsx(Field, { label: "Reserve box", value: quote.reserveBoxId, copy: true }),
752
+ /* @__PURE__ */ jsx(Field, { label: "Task hash", value: quote.taskHash, copy: true }),
753
+ testnetWarning ? /* @__PURE__ */ jsx("div", { style: warningStyle, children: testnetWarning }) : null,
754
+ showPaymentIntent && paymentIntent ? /* @__PURE__ */ jsxs("div", { style: intentStyle, children: [
755
+ /* @__PURE__ */ jsxs("div", { style: intentHeaderStyle, children: [
756
+ /* @__PURE__ */ jsx("strong", { children: "Payment intent" }),
757
+ /* @__PURE__ */ jsx("button", { type: "button", style: copyButtonStyle, onClick: copyPaymentIntent, children: "Copy JSON" })
758
+ ] }),
759
+ /* @__PURE__ */ jsx("code", { style: intentCodeStyle, children: serializeSagePaymentIntent(paymentIntent) })
760
+ ] }) : null,
761
+ props.walletLauncher && paymentIntent ? /* @__PURE__ */ jsx(
762
+ "button",
763
+ {
764
+ type: "button",
765
+ onClick: launchWallet,
766
+ disabled: busy,
767
+ style: secondaryButtonStyle,
768
+ children: paymentInstructions?.walletLauncherLabel ?? "Open wallet flow"
769
+ }
770
+ ) : null,
771
+ /* @__PURE__ */ jsxs("label", { style: labelStyle2, children: [
772
+ paymentInstructions?.noteBoxLabel ?? "Note box id",
773
+ /* @__PURE__ */ jsx(
774
+ "input",
775
+ {
776
+ value: noteBoxId,
777
+ onChange: (e) => setNoteBoxId(e.currentTarget.value),
778
+ placeholder: "Paste 64-char Ergo box id",
779
+ style: inputStyle,
780
+ disabled: busy
781
+ }
782
+ )
783
+ ] }),
784
+ /* @__PURE__ */ jsx(
785
+ "button",
786
+ {
787
+ type: "button",
788
+ onClick: verifyAndContinue,
789
+ disabled: !noteBoxId.trim() || busy,
790
+ style: primaryButtonStyle,
791
+ children: phase === "verifying" ? "Verifying..." : "Verify payment"
792
+ }
793
+ )
794
+ ] }) : null,
795
+ receipt ? /* @__PURE__ */ jsxs("div", { style: receiptPanelStyle, children: [
796
+ /* @__PURE__ */ jsxs("a", { href: receipt.receiptUrl, target: "_blank", rel: "noopener noreferrer", style: receiptStyle, children: [
797
+ "Receipt: ",
798
+ shortId(receipt.receiptId),
799
+ receiptBundle ? ` \xB7 ${receiptBundle.completeness}` : ""
800
+ ] }),
801
+ /* @__PURE__ */ jsx("a", { href: receipt.receiptApiUrl, target: "_blank", rel: "noopener noreferrer", style: receiptApiStyle, children: "machine-readable JSON" })
802
+ ] }) : null,
803
+ error ? /* @__PURE__ */ jsx("div", { style: errorStyle2, children: error }) : null,
804
+ /* @__PURE__ */ jsxs("form", { onSubmit: submit, style: formStyle, children: [
805
+ /* @__PURE__ */ jsx(
806
+ "input",
807
+ {
808
+ value: input,
809
+ onChange: (e) => setInput(e.currentTarget.value),
810
+ placeholder,
811
+ disabled: busy,
812
+ style: inputStyle
813
+ }
814
+ ),
815
+ /* @__PURE__ */ jsx("button", { type: "submit", disabled: !input.trim() || busy, style: sendButtonStyle, children: phase === "quoting" ? "Quoting..." : phase === "streaming" ? "Streaming..." : "Send" })
816
+ ] })
817
+ ] });
818
+ }
819
+ function Field({ label, value, copy = false }) {
820
+ return /* @__PURE__ */ jsxs("div", { style: fieldStyle, children: [
821
+ /* @__PURE__ */ jsx("span", { style: fieldLabelStyle, children: label }),
822
+ /* @__PURE__ */ jsx("code", { style: fieldValueStyle, children: value }),
823
+ copy ? /* @__PURE__ */ jsx("button", { type: "button", style: copyButtonStyle, onClick: () => copyText(value), children: "Copy" }) : null
824
+ ] });
825
+ }
826
+ async function copyText(value) {
827
+ if (typeof navigator !== "undefined" && navigator.clipboard) {
828
+ await navigator.clipboard.writeText(value);
829
+ }
830
+ }
831
+ function shortId(value) {
832
+ return value.length > 18 ? `${value.slice(0, 10)}...${value.slice(-8)}` : value;
833
+ }
834
+ function lastUserQuestion(messages) {
835
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
836
+ const message = messages[i];
837
+ if (message?.role === "user" && message.content.trim()) return message.content.trim();
838
+ }
839
+ return null;
840
+ }
841
+ var rootStyle2 = {
842
+ background: "#070707",
843
+ color: "#f8fafc",
844
+ border: "1px solid rgba(255,255,255,.1)",
845
+ borderRadius: 8,
846
+ padding: 16,
847
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
848
+ boxSizing: "border-box",
849
+ width: "100%",
850
+ maxWidth: 520
851
+ };
852
+ var headerStyle2 = {
853
+ display: "flex",
854
+ justifyContent: "space-between",
855
+ alignItems: "flex-start",
856
+ gap: 12,
857
+ marginBottom: 12
858
+ };
859
+ var eyebrowStyle = {
860
+ color: "#fb923c",
861
+ fontSize: 11,
862
+ letterSpacing: ".16em",
863
+ textTransform: "uppercase",
864
+ marginBottom: 4
865
+ };
866
+ var titleStyle = {
867
+ fontSize: 18,
868
+ lineHeight: 1.2,
869
+ margin: 0
870
+ };
871
+ var badgeStyle = {
872
+ color: "#0f172a",
873
+ background: "#fdba74",
874
+ borderRadius: 4,
875
+ padding: "4px 7px",
876
+ fontSize: 10,
877
+ fontWeight: 800,
878
+ letterSpacing: ".12em"
879
+ };
880
+ var messagesStyle = {
881
+ minHeight: 180,
882
+ maxHeight: 360,
883
+ overflow: "auto",
884
+ display: "flex",
885
+ flexDirection: "column",
886
+ gap: 8,
887
+ padding: "12px 0"
888
+ };
889
+ var emptyStyle2 = {
890
+ color: "#94a3b8",
891
+ border: "1px dashed rgba(148,163,184,.28)",
892
+ borderRadius: 6,
893
+ padding: 12,
894
+ fontSize: 13
895
+ };
896
+ var bubbleBase = {
897
+ borderRadius: 6,
898
+ padding: "9px 10px",
899
+ fontSize: 14,
900
+ lineHeight: 1.45,
901
+ whiteSpace: "pre-wrap"
902
+ };
903
+ var userBubbleStyle = {
904
+ ...bubbleBase,
905
+ alignSelf: "flex-end",
906
+ maxWidth: "88%",
907
+ background: "#fb923c",
908
+ color: "#111827"
909
+ };
910
+ var assistantBubbleStyle = {
911
+ ...bubbleBase,
912
+ alignSelf: "flex-start",
913
+ maxWidth: "92%",
914
+ background: "rgba(255,255,255,.07)",
915
+ color: "#e5e7eb"
916
+ };
917
+ var paymentStyle = {
918
+ border: "1px solid rgba(251,146,60,.35)",
919
+ background: "rgba(251,146,60,.08)",
920
+ borderRadius: 8,
921
+ padding: 12,
922
+ display: "grid",
923
+ gap: 8
924
+ };
925
+ var paymentHeaderStyle = {
926
+ display: "flex",
927
+ justifyContent: "space-between",
928
+ color: "#fed7aa",
929
+ fontSize: 13
930
+ };
931
+ var helperStyle = {
932
+ color: "#fdba74",
933
+ fontSize: 12,
934
+ lineHeight: 1.45,
935
+ margin: 0
936
+ };
937
+ var inlineLinkStyle = {
938
+ color: "#67e8f9",
939
+ textDecoration: "none"
940
+ };
941
+ var labelStyle2 = {
942
+ display: "grid",
943
+ gap: 6,
944
+ color: "#cbd5e1",
945
+ fontSize: 12
946
+ };
947
+ var fieldStyle = {
948
+ display: "grid",
949
+ gridTemplateColumns: "minmax(70px, 88px) minmax(0, 1fr) auto",
950
+ alignItems: "center",
951
+ gap: 8,
952
+ fontSize: 12
953
+ };
954
+ var fieldLabelStyle = {
955
+ color: "#94a3b8"
956
+ };
957
+ var fieldValueStyle = {
958
+ color: "#f8fafc",
959
+ overflow: "hidden",
960
+ textOverflow: "ellipsis",
961
+ whiteSpace: "nowrap",
962
+ fontSize: 11
963
+ };
964
+ var copyButtonStyle = {
965
+ border: "1px solid rgba(255,255,255,.16)",
966
+ background: "rgba(255,255,255,.06)",
967
+ color: "#f8fafc",
968
+ borderRadius: 4,
969
+ padding: "4px 7px",
970
+ cursor: "pointer"
971
+ };
972
+ var formStyle = {
973
+ display: "grid",
974
+ gridTemplateColumns: "minmax(0, 1fr) auto",
975
+ gap: 8,
976
+ marginTop: 12
977
+ };
978
+ var inputStyle = {
979
+ width: "100%",
980
+ boxSizing: "border-box",
981
+ border: "1px solid rgba(255,255,255,.16)",
982
+ background: "#050505",
983
+ color: "#f8fafc",
984
+ borderRadius: 6,
985
+ padding: "10px 11px",
986
+ fontSize: 14
987
+ };
988
+ var sendButtonStyle = {
989
+ border: 0,
990
+ background: "#fb923c",
991
+ color: "#111827",
992
+ borderRadius: 6,
993
+ padding: "0 14px",
994
+ fontWeight: 800,
995
+ cursor: "pointer"
996
+ };
997
+ var primaryButtonStyle = {
998
+ ...sendButtonStyle,
999
+ padding: "10px 12px"
1000
+ };
1001
+ var secondaryButtonStyle = {
1002
+ border: "1px solid rgba(103,232,249,.28)",
1003
+ background: "rgba(103,232,249,.08)",
1004
+ color: "#cffafe",
1005
+ borderRadius: 6,
1006
+ padding: "10px 12px",
1007
+ fontWeight: 800,
1008
+ cursor: "pointer"
1009
+ };
1010
+ var warningStyle = {
1011
+ color: "#fde68a",
1012
+ background: "rgba(245,158,11,.1)",
1013
+ border: "1px solid rgba(245,158,11,.24)",
1014
+ borderRadius: 6,
1015
+ padding: "8px 9px",
1016
+ fontSize: 12,
1017
+ lineHeight: 1.45
1018
+ };
1019
+ var intentStyle = {
1020
+ border: "1px solid rgba(255,255,255,.12)",
1021
+ background: "rgba(255,255,255,.04)",
1022
+ borderRadius: 6,
1023
+ padding: 10,
1024
+ display: "grid",
1025
+ gap: 8
1026
+ };
1027
+ var intentHeaderStyle = {
1028
+ display: "flex",
1029
+ justifyContent: "space-between",
1030
+ alignItems: "center",
1031
+ gap: 8,
1032
+ color: "#e2e8f0",
1033
+ fontSize: 12
1034
+ };
1035
+ var intentCodeStyle = {
1036
+ display: "block",
1037
+ maxHeight: 130,
1038
+ overflow: "auto",
1039
+ whiteSpace: "pre-wrap",
1040
+ wordBreak: "break-word",
1041
+ color: "#cbd5e1",
1042
+ fontSize: 10,
1043
+ lineHeight: 1.45
1044
+ };
1045
+ var receiptStyle = {
1046
+ display: "inline-flex",
1047
+ color: "#67e8f9",
1048
+ fontSize: 13,
1049
+ textDecoration: "none"
1050
+ };
1051
+ var receiptPanelStyle = {
1052
+ display: "flex",
1053
+ alignItems: "center",
1054
+ flexWrap: "wrap",
1055
+ gap: 10,
1056
+ marginTop: 10,
1057
+ border: "1px solid rgba(103,232,249,.22)",
1058
+ background: "rgba(103,232,249,.07)",
1059
+ borderRadius: 6,
1060
+ padding: "9px 10px"
1061
+ };
1062
+ var receiptApiStyle = {
1063
+ color: "#cbd5e1",
1064
+ fontSize: 12,
1065
+ textDecoration: "none"
1066
+ };
1067
+ var errorStyle2 = {
1068
+ color: "#fecaca",
1069
+ background: "rgba(239,68,68,.12)",
1070
+ border: "1px solid rgba(239,68,68,.25)",
1071
+ borderRadius: 6,
1072
+ padding: 10,
1073
+ marginTop: 10,
1074
+ fontSize: 13
1075
+ };
294
1076
 
295
- export { DEFAULT_API_BASE, DEFAULT_LIMIT, DEFAULT_REFRESH_MS, SageActivityFeed };
1077
+ export { DEFAULT_API_BASE, DEFAULT_LIMIT, DEFAULT_REFRESH_MS, SageActivityFeed, SagePaymentWidget };
296
1078
  //# sourceMappingURL=react.js.map
297
1079
  //# sourceMappingURL=react.js.map