@pagelines/sdk 1.0.478 → 1.0.479

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/sdkClient.js CHANGED
@@ -1,28 +1,28 @@
1
1
  var V = Object.defineProperty;
2
- var Z = (l, e, t) => e in l ? V(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t;
3
- var d = (l, e) => V(l, "name", { value: e, configurable: !0 });
4
- var n = (l, e, t) => Z(l, typeof e != "symbol" ? e + "" : e, t);
5
- import { APP_PORT as ee, APP_PROD_URL as te, createRefreshingFetch as re, cookieUtil as b, createLogger as oe, shortId as se, objectId as O, SettingsObject as ae } from "@pagelines/core";
6
- import { watch as R, ref as A, computed as Q } from "vue";
7
- import { hc as ie } from "hono/client";
8
- function y(l, e) {
9
- return l || (e ? `http://localhost:${ee}` : te);
2
+ var ee = (l, e, t) => e in l ? V(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t;
3
+ var g = (l, e) => V(l, "name", { value: e, configurable: !0 });
4
+ var n = (l, e, t) => ee(l, typeof e != "symbol" ? e + "" : e, t);
5
+ import { APP_PORT as te, APP_PROD_URL as re, createRefreshingFetch as se, cookieUtil as b, createLogger as oe, shortId as ae, objectId as R, SettingsObject as ie } from "@pagelines/core";
6
+ import { watch as P, ref as A, computed as Q } from "vue";
7
+ import { hc as ne } from "hono/client";
8
+ function w(l, e) {
9
+ return l || (e ? `http://localhost:${te}` : re);
10
10
  }
11
- d(y, "resolveApiBase");
12
- function ne(l, e, t) {
13
- const r = y(l.apiBase, l.isDev), o = t ? re({
11
+ g(w, "resolveApiBase");
12
+ function ce(l, e, t) {
13
+ const r = w(l.apiBase, l.isDev), s = t ? se({
14
14
  fetch: globalThis.fetch.bind(globalThis),
15
15
  getDeviceId: t.getDeviceId,
16
16
  refreshUrl: `${r}/api/auth/refresh`,
17
17
  onAccessTokenRefreshed: t.onAccessTokenRefreshed,
18
18
  onTerminalFailure: t.onTerminalFailure
19
19
  }) : globalThis.fetch.bind(globalThis);
20
- return ie(r, {
21
- fetch: /* @__PURE__ */ d(async (c, h) => {
22
- const a = b.getAuthToken(), i = await o(c, {
23
- ...h,
20
+ return ne(r, {
21
+ fetch: /* @__PURE__ */ g(async (i, d) => {
22
+ const a = b.getAuthToken(), c = await s(i, {
23
+ ...d,
24
24
  headers: {
25
- ...h?.headers,
25
+ ...d?.headers,
26
26
  "Content-Type": "application/json",
27
27
  // Only include Authorization header if token exists
28
28
  ...a && { Authorization: `Bearer ${a}` }
@@ -34,20 +34,20 @@ function ne(l, e, t) {
34
34
  credentials: "include"
35
35
  });
36
36
  if (e) {
37
- const f = i.json.bind(i);
38
- i.json = async () => {
39
- const u = await f();
37
+ const h = c.json.bind(c);
38
+ c.json = async () => {
39
+ const u = await h();
40
40
  return typeof u == "object" && u !== null && "ok" in u && ("user" in u || "token" in u) && e(u), u;
41
41
  };
42
42
  }
43
- return i;
43
+ return c;
44
44
  }, "fetch")
45
45
  });
46
46
  }
47
- d(ne, "createApiClient");
48
- const ce = /* @__PURE__ */ Symbol("clean");
49
- let p = [], x = 0;
50
- const U = 4, le = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal = { epoch: 0 }), G = /* @__PURE__ */ d(/* @__NO_SIDE_EFFECTS__ */ (l) => {
47
+ g(ce, "createApiClient");
48
+ const le = /* @__PURE__ */ Symbol("clean");
49
+ let m = [], k = 0;
50
+ const U = 4, ue = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal = { epoch: 0 }), G = /* @__PURE__ */ g(/* @__NO_SIDE_EFFECTS__ */ (l) => {
51
51
  let e = [], t = {
52
52
  get() {
53
53
  return t.lc || t.listen(() => {
@@ -57,25 +57,25 @@ const U = 4, le = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
57
57
  lc: 0,
58
58
  listen(r) {
59
59
  return t.lc = e.push(r), () => {
60
- for (let s = x + U; s < p.length; )
61
- p[s] === r ? p.splice(s, U) : s += U;
62
- let o = e.indexOf(r);
63
- ~o && (e.splice(o, 1), --t.lc || t.off());
60
+ for (let o = k + U; o < m.length; )
61
+ m[o] === r ? m.splice(o, U) : o += U;
62
+ let s = e.indexOf(r);
63
+ ~s && (e.splice(s, 1), --t.lc || t.off());
64
64
  };
65
65
  },
66
- notify(r, o) {
67
- le.epoch++;
68
- let s = !p.length;
69
- for (let c of e)
70
- p.push(c, t.value, r, o);
71
- if (s) {
72
- for (x = 0; x < p.length; x += U)
73
- p[x](
74
- p[x + 1],
75
- p[x + 2],
76
- p[x + 3]
66
+ notify(r, s) {
67
+ ue.epoch++;
68
+ let o = !m.length;
69
+ for (let i of e)
70
+ m.push(i, t.value, r, s);
71
+ if (o) {
72
+ for (k = 0; k < m.length; k += U)
73
+ m[k](
74
+ m[k + 1],
75
+ m[k + 2],
76
+ m[k + 3]
77
77
  );
78
- p.length = 0;
78
+ m.length = 0;
79
79
  }
80
80
  },
81
81
  /* It will be called on last listener unsubscribing.
@@ -83,19 +83,19 @@ const U = 4, le = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
83
83
  off() {
84
84
  },
85
85
  set(r) {
86
- let o = t.value;
87
- o !== r && (t.value = r, t.notify(o));
86
+ let s = t.value;
87
+ s !== r && (t.value = r, t.notify(s));
88
88
  },
89
89
  subscribe(r) {
90
- let o = t.listen(r);
91
- return r(t.value), o;
90
+ let s = t.listen(r);
91
+ return r(t.value), s;
92
92
  },
93
93
  value: l
94
94
  };
95
- return process.env.NODE_ENV !== "production" && (t[ce] = () => {
95
+ return process.env.NODE_ENV !== "production" && (t[le] = () => {
96
96
  e = [], t.lc = 0, t.off();
97
97
  }), t;
98
- }, "atom"), w = globalThis, E = w.__PL_AUTH_USER__ ?? (w.__PL_AUTH_USER__ = /* @__PURE__ */ G(void 0)), T = w.__PL_AUTH_TOKEN__ ?? (w.__PL_AUTH_TOKEN__ = /* @__PURE__ */ G(null)), $ = w.__PL_AUTH_DEVICE_ID__ ?? (w.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ G(null)), W = class W {
98
+ }, "atom"), x = globalThis, E = x.__PL_AUTH_USER__ ?? (x.__PL_AUTH_USER__ = /* @__PURE__ */ G(void 0)), T = x.__PL_AUTH_TOKEN__ ?? (x.__PL_AUTH_TOKEN__ = /* @__PURE__ */ G(null)), $ = x.__PL_AUTH_DEVICE_ID__ ?? (x.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ G(null)), W = class W {
99
99
  constructor() {
100
100
  n(this, "logger", oe("SDKStorage"));
101
101
  }
@@ -109,13 +109,13 @@ const U = 4, le = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
109
109
  * Sync Vue reactive refs with global nanostores for cross-bundle persistence.
110
110
  */
111
111
  syncWithGlobalStores(e) {
112
- const { activeUser: t, token: r, deviceId: o } = e, s = E.get(), c = T.get(), h = $.get();
113
- s && (t.value = s), c && (r.value = c), h && (o.value = h), R(t, (a) => E.set(a), { immediate: !0 }), R(r, (a) => T.set(a), { immediate: !0 }), R(o, (a) => $.set(a), { immediate: !0 }), E.subscribe((a) => {
112
+ const { activeUser: t, token: r, deviceId: s } = e, o = E.get(), i = T.get(), d = $.get();
113
+ o && (t.value = o), i && (r.value = i), d && (s.value = d), P(t, (a) => E.set(a), { immediate: !0 }), P(r, (a) => T.set(a), { immediate: !0 }), P(s, (a) => $.set(a), { immediate: !0 }), E.subscribe((a) => {
114
114
  a !== t.value && (t.value = a);
115
115
  }), T.subscribe((a) => {
116
116
  a !== r.value && (r.value = a);
117
117
  }), $.subscribe((a) => {
118
- a !== o.value && (o.value = a);
118
+ a !== s.value && (s.value = a);
119
119
  });
120
120
  }
121
121
  /**
@@ -130,10 +130,10 @@ const U = 4, le = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
130
130
  const r = b.getDeviceId();
131
131
  if (r && (e.deviceId.value = r), this.isLocalStorageFunctional())
132
132
  try {
133
- const o = localStorage.getItem("pagelines-user");
134
- o && (e.activeUser.value = JSON.parse(o));
135
- } catch (o) {
136
- this.logger.error("Failed to load user from localStorage", { data: o });
133
+ const s = localStorage.getItem("pagelines-user");
134
+ s && (e.activeUser.value = JSON.parse(s));
135
+ } catch (s) {
136
+ this.logger.error("Failed to load user from localStorage", { data: s });
137
137
  }
138
138
  }
139
139
  /**
@@ -188,12 +188,12 @@ const U = 4, le = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
188
188
  }
189
189
  }
190
190
  };
191
- d(W, "SDKStorage");
192
- let P = W;
191
+ g(W, "SDKStorage");
192
+ let O = W;
193
193
  const X = [
194
- "Deploying your server...",
195
- "Setting up your workspace...",
196
- "Installing tools...",
194
+ "Setting up your assistant...",
195
+ "Preparing your workspace...",
196
+ "Connecting tools...",
197
197
  "Almost ready..."
198
198
  ], M = class M {
199
199
  constructor(e) {
@@ -201,7 +201,7 @@ const X = [
201
201
  this.ctx = e;
202
202
  }
203
203
  async create(e) {
204
- const t = e.orgId || this.resolveOrgId(), r = y(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/agent`, {
204
+ const t = e.orgId || this.resolveOrgId(), r = w(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${r}/api/agent`, {
205
205
  method: "POST",
206
206
  headers: {
207
207
  "Content-Type": "application/json",
@@ -209,24 +209,24 @@ const X = [
209
209
  },
210
210
  body: JSON.stringify({ name: e.name, orgId: t })
211
211
  })).json();
212
- if (!s.ok || !s.data?.[0]) {
213
- const c = s.error || "Failed to create agent";
214
- throw this.ctx.error.value = c, new Error(c);
212
+ if (!o.ok || !o.data?.[0]) {
213
+ const i = o.error || "Failed to create agent";
214
+ throw this.ctx.error.value = i, new Error(i);
215
215
  }
216
- return this.ctx.processApiResponse(s), s.data[0];
216
+ return this.ctx.processApiResponse(o), o.data[0];
217
217
  }
218
218
  async getStatus(e) {
219
- const t = y(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/agent/${e.agentId}/status`, {
219
+ const t = w(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${t}/api/agent/${e.agentId}/status`, {
220
220
  headers: {
221
221
  ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
222
222
  }
223
223
  })).json();
224
- return !o.ok || !o.data ? { status: "unknown", ready: !1, error: "Failed to check status" } : o.data;
224
+ return !s.ok || !s.data ? { status: "unknown", ready: !1, error: "Failed to check status" } : s.data;
225
225
  }
226
226
  async waitUntilReady(e) {
227
- const { agentId: t, onStatus: r, timeoutMs: o = 3e5, pollIntervalMs: s = 3e3 } = e, c = Date.now();
228
- let h = 0;
229
- for (; Date.now() - c < o; ) {
227
+ const { agentId: t, onStatus: r, timeoutMs: s = 3e5, pollIntervalMs: o = 3e3 } = e, i = Date.now();
228
+ let d = 0;
229
+ for (; Date.now() - i < s; ) {
230
230
  const a = await this.getStatus({ agentId: t });
231
231
  if (a.ready) {
232
232
  r?.("Ready!");
@@ -234,24 +234,24 @@ const X = [
234
234
  }
235
235
  if (a.status === "error")
236
236
  throw new Error(a.error || "Provisioning failed");
237
- r && h < X.length && (r(X[h]), h++), await new Promise((i) => setTimeout(i, s));
237
+ r && d < X.length && (r(X[d]), d++), await new Promise((c) => setTimeout(c, o));
238
238
  }
239
239
  throw new Error("Agent provisioning timed out — please try again");
240
240
  }
241
241
  /** Send a typed webhook event to a bot agent. No auth required — the proxy is public. */
242
242
  async webhook(e) {
243
- const r = `${y(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/agents/${e.agentId}/webhook`, o = { type: e.type, data: e.data };
244
- e.meta && (o.meta = e.meta);
245
- const s = await fetch(r, {
243
+ const r = `${w(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/agents/${e.agentId}/webhook`, s = { type: e.type, data: e.data };
244
+ e.meta && (s.meta = e.meta);
245
+ const o = await fetch(r, {
246
246
  method: "POST",
247
247
  headers: { "Content-Type": "application/json" },
248
- body: JSON.stringify(o)
248
+ body: JSON.stringify(s)
249
249
  });
250
- if (!s.ok) {
251
- const c = await s.text().catch(() => "Unknown error");
252
- throw new Error(`Webhook delivery failed (${s.status}): ${c.slice(0, 200)}`);
250
+ if (!o.ok) {
251
+ const i = await o.text().catch(() => "Unknown error");
252
+ throw new Error(`Webhook delivery failed (${o.status}): ${i.slice(0, 200)}`);
253
253
  }
254
- return s.json();
254
+ return o.json();
255
255
  }
256
256
  resolveOrgId() {
257
257
  const t = this.ctx.activeUser.value?.orgs?.[0]?.orgId;
@@ -260,7 +260,7 @@ const X = [
260
260
  return t;
261
261
  }
262
262
  };
263
- d(M, "AgentClient");
263
+ g(M, "AgentClient");
264
264
  let _ = M;
265
265
  async function S(l, e) {
266
266
  l.loading.value = !0, l.error.value = null;
@@ -270,7 +270,7 @@ async function S(l, e) {
270
270
  l.loading.value = !1;
271
271
  }
272
272
  }
273
- d(S, "withLoadingState");
273
+ g(S, "withLoadingState");
274
274
  const z = class z {
275
275
  constructor(e) {
276
276
  n(this, "ctx");
@@ -294,15 +294,15 @@ const z = class z {
294
294
  async verifyCode(e, t) {
295
295
  return S(this.ctx, async () => {
296
296
  try {
297
- const o = await (await this.ctx.api.auth["verify-code"].$post({
297
+ const s = await (await this.ctx.api.auth["verify-code"].$post({
298
298
  json: { email: e, code: t }
299
299
  })).json();
300
- if (!o.ok)
301
- throw this.ctx.error.value = o.error, new Error(o.error);
300
+ if (!s.ok)
301
+ throw this.ctx.error.value = s.error, new Error(s.error);
302
302
  } catch (r) {
303
303
  this.ctx.logger.error("Verify code error", { data: r });
304
- const o = r instanceof Error ? r.message : "Failed to verify code";
305
- throw this.ctx.error.value = o, r;
304
+ const s = r instanceof Error ? r.message : "Failed to verify code";
305
+ throw this.ctx.error.value = s, r;
306
306
  }
307
307
  });
308
308
  }
@@ -361,45 +361,45 @@ const z = class z {
361
361
  this.ctx.logger.error("loginWithGoogle: Only available in browser");
362
362
  return;
363
363
  }
364
- const t = y(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, o = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, s = 500, c = 600, h = window.screenX + (window.outerWidth - s) / 2, a = window.screenY + (window.outerHeight - c) / 2, i = window.open(
365
- o,
364
+ const t = w(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, s = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, o = 500, i = 600, d = window.screenX + (window.outerWidth - o) / 2, a = window.screenY + (window.outerHeight - i) / 2, c = window.open(
365
+ s,
366
366
  "google-auth",
367
- `width=${s},height=${c},left=${h},top=${a},popup=yes`
367
+ `width=${o},height=${i},left=${d},top=${a},popup=yes`
368
368
  );
369
- if (!i) {
369
+ if (!c) {
370
370
  const v = "Popup was blocked. Please allow popups for this site.";
371
371
  this.ctx.error.value = v, e?.onError?.(v);
372
372
  return;
373
373
  }
374
- const f = /* @__PURE__ */ d((v) => {
375
- const k = new URL(t).origin;
376
- if (v.origin === k) {
374
+ const h = /* @__PURE__ */ g((v) => {
375
+ const I = new URL(t).origin;
376
+ if (v.origin === I) {
377
377
  if (v.data?.type === "auth-success") {
378
- window.removeEventListener("message", f);
379
- const { token: g, user: I } = v.data;
380
- this.ctx.processApiResponse({ ok: !0, data: {}, token: g, user: I }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(I);
378
+ window.removeEventListener("message", h);
379
+ const { token: p, user: f } = v.data;
380
+ this.ctx.processApiResponse({ ok: !0, data: {}, token: p, user: f }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(f);
381
381
  } else if (v.data?.type === "auth-error") {
382
- window.removeEventListener("message", f);
383
- const g = v.data.error || "Google authentication failed";
384
- this.ctx.error.value = g, this.ctx.logger.error("Google login failed", { error: g }), e?.onError?.(g);
382
+ window.removeEventListener("message", h);
383
+ const p = v.data.error || "Google authentication failed";
384
+ this.ctx.error.value = p, this.ctx.logger.error("Google login failed", { error: p }), e?.onError?.(p);
385
385
  }
386
386
  }
387
387
  }, "handler");
388
- window.addEventListener("message", f);
388
+ window.addEventListener("message", h);
389
389
  const u = setInterval(() => {
390
- i.closed && (clearInterval(u), window.removeEventListener("message", f));
390
+ c.closed && (clearInterval(u), window.removeEventListener("message", h));
391
391
  }, 500);
392
392
  }
393
393
  };
394
- d(z, "AuthClient");
394
+ g(z, "AuthClient");
395
395
  let j = z;
396
- const J = class J {
396
+ const q = class q {
397
397
  constructor(e) {
398
398
  n(this, "ctx");
399
399
  this.ctx = e;
400
400
  }
401
401
  async startTrial(e) {
402
- const t = this.resolveOrgId(), r = y(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/billing/checkout/create`, {
402
+ const t = this.resolveOrgId(), r = w(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${r}/api/billing/checkout/create`, {
403
403
  method: "POST",
404
404
  headers: {
405
405
  "Content-Type": "application/json",
@@ -411,36 +411,36 @@ const J = class J {
411
411
  ...e?.planKey && { planKey: e.planKey }
412
412
  })
413
413
  })).json();
414
- if (!s.ok || !s.data?.url) {
415
- const c = s.error || "Failed to create checkout session";
416
- throw this.ctx.error.value = c, new Error(c);
414
+ if (!o.ok || !o.data?.url) {
415
+ const i = o.error || "Failed to create checkout session";
416
+ throw this.ctx.error.value = i, new Error(i);
417
417
  }
418
- window.location.href = s.data.url;
418
+ window.location.href = o.data.url;
419
419
  }
420
420
  async confirmCheckout(e) {
421
421
  return this.getStatus();
422
422
  }
423
423
  async getStatus() {
424
- const e = this.resolveOrgId(), t = y(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/billing/details/${e}`, {
424
+ const e = this.resolveOrgId(), t = w(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${t}/api/billing/details/${e}`, {
425
425
  headers: {
426
426
  ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
427
427
  }
428
428
  })).json();
429
- if (!o.ok || !o.data)
429
+ if (!s.ok || !s.data)
430
430
  return {
431
431
  plan: void 0,
432
432
  status: "none",
433
433
  hasActiveBilling: !1,
434
434
  maxAgents: 0
435
435
  };
436
- const s = ["active", "trialing"];
436
+ const o = ["active", "trialing"];
437
437
  return {
438
- plan: o.data.plan,
439
- status: o.data.status,
440
- hasActiveBilling: s.includes(o.data.status),
441
- maxAgents: o.data.maxAgents,
442
- ...o.data.trialEnd && { trialEnd: o.data.trialEnd },
443
- ...o.data.trialDaysRemaining !== void 0 && { trialDaysRemaining: o.data.trialDaysRemaining }
438
+ plan: s.data.plan,
439
+ status: s.data.status,
440
+ hasActiveBilling: o.includes(s.data.status),
441
+ maxAgents: s.data.maxAgents,
442
+ ...s.data.trialEnd && { trialEnd: s.data.trialEnd },
443
+ ...s.data.trialDaysRemaining !== void 0 && { trialDaysRemaining: s.data.trialDaysRemaining }
444
444
  };
445
445
  }
446
446
  resolveOrgId() {
@@ -450,16 +450,16 @@ const J = class J {
450
450
  return t;
451
451
  }
452
452
  };
453
- d(J, "BillingClient");
454
- let F = J;
455
- const ue = /* @__PURE__ */ new Set(["message", "message_delta", "working_state", "working_end", "error", "stream_end"]);
456
- function de(l) {
453
+ g(q, "BillingClient");
454
+ let C = q;
455
+ const de = /* @__PURE__ */ new Set(["message", "message_delta", "working_state", "working_end", "error", "stream_end"]);
456
+ function Y(l) {
457
457
  const e = l.split(`
458
- `).filter((o) => o.length > 0);
458
+ `).filter((s) => s.length > 0);
459
459
  let t, r;
460
- for (const o of e)
461
- o.startsWith("event:") ? t = o.slice(6).trim() : o.startsWith("data:") && (r = o.slice(5).trim());
462
- if (!t || r === void 0 || !ue.has(t))
460
+ for (const s of e)
461
+ s.startsWith("event:") ? t = s.slice(6).trim() : s.startsWith("data:") && (r = s.slice(5).trim());
462
+ if (!t || r === void 0 || !de.has(t))
463
463
  return null;
464
464
  try {
465
465
  return { event: t, data: JSON.parse(r) };
@@ -467,76 +467,85 @@ function de(l) {
467
467
  return null;
468
468
  }
469
469
  }
470
- d(de, "parseChatEvent");
471
- const q = class q {
470
+ g(Y, "parseChatEvent");
471
+ const J = class J {
472
472
  constructor(e) {
473
473
  n(this, "ctx");
474
474
  this.ctx = e;
475
475
  }
476
476
  /**
477
- * Public/visitor chat — anonymous chat against an agent's public handle.
478
- * Stays on the legacy `AgentChatServer` route for now; substrate doesn't
479
- * support visitor identities yet (deferred per `plans/features/chat.md`).
477
+ * Public/visitor chat — anonymous chat against an agent's public handle,
478
+ * routed through the messaging substrate. Same SSE wire format as
479
+ * `chatStreamAuthenticated` the only difference is the route (no auth,
480
+ * handle-based lookup, anonymousId instead of userId).
481
+ *
482
+ * The visitor identity is `anonymousId` — caller is responsible for
483
+ * generating + persisting it (typically `sdk.generateAnonId()` which
484
+ * stores a stable ID in localStorage).
480
485
  */
481
- async chatStream(e) {
482
- const r = `${y(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat/stream`;
486
+ async chatStreamPublic(e) {
487
+ const r = `${w(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat/v2/stream`;
488
+ let s = "", o = !1, i = !1, d;
483
489
  try {
484
- const o = await fetch(r, {
490
+ const a = await fetch(r, {
485
491
  method: "POST",
486
492
  headers: { "Content-Type": "application/json" },
487
493
  body: JSON.stringify({
488
494
  message: e.message,
489
- conversationId: e.conversationId,
490
- history: e.history,
491
- visitorId: e.visitorId,
492
- context: e.context,
493
- attachments: e.attachments
495
+ anonymousId: e.anonymousId,
496
+ ...e.attachments?.length ? { attachments: e.attachments } : {},
497
+ ...e.context ? { context: e.context } : {}
494
498
  })
495
499
  });
496
- if (!o.ok) {
497
- const i = await o.json().catch(() => ({ error: "Request failed" }));
498
- e.onError(i.error || `HTTP ${o.status}`);
500
+ if (!a.ok) {
501
+ const u = await a.json().catch(() => ({ error: "Request failed" }));
502
+ e.onError(u.error || `HTTP ${a.status}`);
499
503
  return;
500
504
  }
501
- const s = o.body?.getReader();
502
- if (!s) {
505
+ if (s = a.headers.get("X-Conversation-Id") || "", d = a.body?.getReader(), !d) {
503
506
  e.onError("No response stream");
504
507
  return;
505
508
  }
506
509
  const c = new TextDecoder();
507
- let h = "", a = e.conversationId || "";
508
- for (; ; ) {
509
- const { done: i, value: f } = await s.read();
510
- if (i)
510
+ let h = "";
511
+ e: for (; ; ) {
512
+ const { done: u, value: v } = await d.read();
513
+ if (u)
511
514
  break;
512
- h += c.decode(f, { stream: !0 });
513
- const u = h.split(`
515
+ h += c.decode(v, { stream: !0 });
516
+ let I = h.indexOf(`
517
+
514
518
  `);
515
- h = u.pop() || "";
516
- for (const v of u) {
517
- if (!v.startsWith("data: "))
518
- continue;
519
- const k = v.slice(6).trim();
520
- if (k === "[DONE]") {
521
- e.onDone(a);
522
- return;
523
- }
524
- try {
525
- const g = JSON.parse(k);
526
- if (g.pl_status) {
527
- e.onStatus?.(g.pl_status);
528
- continue;
529
- }
530
- g.pl_metadata?.conversationId && (a = g.pl_metadata.conversationId);
531
- const I = g.choices?.[0]?.delta;
532
- I?.content && e.onDelta(I.content);
533
- } catch {
519
+ for (; I !== -1; ) {
520
+ const p = h.slice(0, I);
521
+ h = h.slice(I + 2);
522
+ const f = Y(p);
523
+ if (f) {
524
+ if (f.event === "working_state")
525
+ e.onStatus?.(f.data.description);
526
+ else if (f.event === "message_delta")
527
+ e.onDelta(f.data.delta);
528
+ else if (f.event === "error") {
529
+ o = !0, e.onError(f.data.message);
530
+ break e;
531
+ } else if (f.event === "message" && f.data.message.role === "assistant")
532
+ i = !0;
533
+ else if (f.event === "stream_end")
534
+ break e;
534
535
  }
536
+ I = h.indexOf(`
537
+
538
+ `);
535
539
  }
536
540
  }
537
- e.onDone(a);
538
- } catch (o) {
539
- e.onError(o instanceof Error ? o.message : "Stream failed");
541
+ !o && i ? e.onDone(s) : o || e.onError("Stream ended before reply arrived");
542
+ } catch (a) {
543
+ e.onError(a instanceof Error ? a.message : "Stream failed");
544
+ } finally {
545
+ try {
546
+ await d?.cancel();
547
+ } catch {
548
+ }
540
549
  }
541
550
  }
542
551
  /**
@@ -546,72 +555,72 @@ const q = class q {
546
555
  * Mirrors `src/modules/agent/client.ts → sendChatMessageStream`.
547
556
  */
548
557
  async chatStreamAuthenticated(e) {
549
- const t = y(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {}, o = `nonce_${se(16)}`;
550
- let s;
558
+ const t = w(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {}, s = `nonce_${ae(16)}`;
559
+ let o;
551
560
  try {
552
- const i = await fetch(`${t}/api/messages`, {
561
+ const c = await fetch(`${t}/api/messages`, {
553
562
  method: "POST",
554
563
  headers: { "Content-Type": "application/json", ...r },
555
- body: JSON.stringify({ agentId: e.agentId, content: e.message, clientNonce: o })
556
- }), f = await i.json();
557
- if (!f.ok) {
558
- e.onError(f.error || `Send failed: HTTP ${i.status}`);
564
+ body: JSON.stringify({ agentId: e.agentId, content: e.message, clientNonce: s })
565
+ }), h = await c.json();
566
+ if (!h.ok) {
567
+ e.onError(h.error || `Send failed: HTTP ${c.status}`);
559
568
  return;
560
569
  }
561
- s = f.data;
562
- } catch (i) {
563
- e.onError(i instanceof Error ? i.message : "Send failed");
570
+ o = h.data;
571
+ } catch (c) {
572
+ e.onError(c instanceof Error ? c.message : "Send failed");
564
573
  return;
565
574
  }
566
- let c = !1, h = !1, a;
575
+ let i = !1, d = !1, a;
567
576
  try {
568
- const i = await fetch(`${t}/api/chat/${encodeURIComponent(e.agentId)}/stream?since=${encodeURIComponent(s.sequence)}`, {
577
+ const c = await fetch(`${t}/api/chat/${encodeURIComponent(e.agentId)}/stream?since=${encodeURIComponent(o.sequence)}`, {
569
578
  headers: r
570
579
  });
571
- if (!i.ok) {
572
- e.onError(`Stream failed: HTTP ${i.status}`);
580
+ if (!c.ok) {
581
+ e.onError(`Stream failed: HTTP ${c.status}`);
573
582
  return;
574
583
  }
575
- if (a = i.body?.getReader(), !a) {
584
+ if (a = c.body?.getReader(), !a) {
576
585
  e.onError("No response stream");
577
586
  return;
578
587
  }
579
- const f = new TextDecoder();
588
+ const h = new TextDecoder();
580
589
  let u = "";
581
590
  e: for (; ; ) {
582
- const { done: v, value: k } = await a.read();
591
+ const { done: v, value: I } = await a.read();
583
592
  if (v)
584
593
  break;
585
- u += f.decode(k, { stream: !0 });
586
- let g = u.indexOf(`
594
+ u += h.decode(I, { stream: !0 });
595
+ let p = u.indexOf(`
587
596
 
588
597
  `);
589
- for (; g !== -1; ) {
590
- const I = u.slice(0, g);
591
- u = u.slice(g + 2);
592
- const m = de(I);
593
- if (m) {
594
- if (m.event === "working_state")
595
- e.onStatus?.(m.data.description);
596
- else if (m.event === "message_delta")
597
- e.onDelta(m.data.delta);
598
- else if (m.event === "error") {
599
- c = !0, e.onError(m.data.message);
598
+ for (; p !== -1; ) {
599
+ const f = u.slice(0, p);
600
+ u = u.slice(p + 2);
601
+ const y = Y(f);
602
+ if (y) {
603
+ if (y.event === "working_state")
604
+ e.onStatus?.(y.data.description);
605
+ else if (y.event === "message_delta")
606
+ e.onDelta(y.data.delta);
607
+ else if (y.event === "error") {
608
+ i = !0, e.onError(y.data.message);
600
609
  break e;
601
- } else if (m.event === "message" && m.data.message.role === "assistant") {
602
- h = !0;
610
+ } else if (y.event === "message" && y.data.message.role === "assistant") {
611
+ d = !0;
603
612
  break e;
604
- } else if (m.event === "stream_end")
613
+ } else if (y.event === "stream_end")
605
614
  break e;
606
615
  }
607
- g = u.indexOf(`
616
+ p = u.indexOf(`
608
617
 
609
618
  `);
610
619
  }
611
620
  }
612
- !c && h ? e.onDone(s.conversationId) : c || e.onError("Stream ended before reply arrived");
613
- } catch (i) {
614
- e.onError(i instanceof Error ? i.message : "Stream failed");
621
+ !i && d ? e.onDone(o.conversationId) : i || e.onError("Stream ended before reply arrived");
622
+ } catch (c) {
623
+ e.onError(c instanceof Error ? c.message : "Stream failed");
615
624
  } finally {
616
625
  try {
617
626
  await a?.cancel();
@@ -620,9 +629,9 @@ const q = class q {
620
629
  }
621
630
  }
622
631
  async chatMessage(e) {
623
- const r = `${y(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat`;
632
+ const r = `${w(this.ctx.apiBase, this.ctx.isDev)}/api/agent/public/${encodeURIComponent(e.handle)}/chat`;
624
633
  try {
625
- const s = await (await fetch(r, {
634
+ const o = await (await fetch(r, {
626
635
  method: "POST",
627
636
  headers: { "Content-Type": "application/json" },
628
637
  body: JSON.stringify({
@@ -632,22 +641,22 @@ const q = class q {
632
641
  context: e.context
633
642
  })
634
643
  })).json();
635
- if (!s.ok || !s.data) {
636
- this.ctx.logger.error("chatMessage failed", { error: !s.ok && "error" in s ? s.error : "Unknown" });
644
+ if (!o.ok || !o.data) {
645
+ this.ctx.logger.error("chatMessage failed", { error: !o.ok && "error" in o ? o.error : "Unknown" });
637
646
  return;
638
647
  }
639
648
  return {
640
- conversationId: s.data.conversationId,
641
- content: s.data.message.content
649
+ conversationId: o.data.conversationId,
650
+ content: o.data.message.content
642
651
  };
643
- } catch (o) {
644
- this.ctx.logger.error("chatMessage error", { error: o });
652
+ } catch (s) {
653
+ this.ctx.logger.error("chatMessage error", { error: s });
645
654
  return;
646
655
  }
647
656
  }
648
657
  };
649
- d(q, "ChatClient");
650
- let C = q;
658
+ g(J, "ChatClient");
659
+ let F = J;
651
660
  const K = class K {
652
661
  constructor(e) {
653
662
  n(this, "ctx");
@@ -692,7 +701,7 @@ const K = class K {
692
701
  generateAnonId() {
693
702
  const e = "pagelinesAnonId";
694
703
  let t = this.ctx.storage.getItem(e);
695
- return t || (t = O({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
704
+ return t || (t = R({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
696
705
  }
697
706
  track(e) {
698
707
  try {
@@ -707,7 +716,7 @@ const K = class K {
707
716
  }
708
717
  }
709
718
  };
710
- d(K, "UserClient");
719
+ g(K, "UserClient");
711
720
  let L = K;
712
721
  const H = class H {
713
722
  constructor() {
@@ -724,9 +733,9 @@ const H = class H {
724
733
  typeof window < "u" && delete globalThis[this.key];
725
734
  }
726
735
  };
727
- d(H, "SDKGlobal");
736
+ g(H, "SDKGlobal");
728
737
  let N = H;
729
- const D = new N(), B = class B extends ae {
738
+ const D = new N(), B = class B extends ie {
730
739
  constructor(t = {}) {
731
740
  const r = D.get();
732
741
  if (r)
@@ -743,9 +752,9 @@ const D = new N(), B = class B extends ae {
743
752
  n(this, "error", A(null));
744
753
  n(this, "apiBase", this.settings.apiBase || void 0);
745
754
  // Storage handler for persistence
746
- n(this, "storage", new P());
755
+ n(this, "storage", new O());
747
756
  // Auto-managed session ID for usage tracking
748
- n(this, "sessionId", O({ prefix: "ses" }));
757
+ n(this, "sessionId", R({ prefix: "ses" }));
749
758
  // Typed Hono RPC client - uses SDKAppType (auth/self/usage routes only)
750
759
  // Initialized in constructor (definite assignment via singleton pattern)
751
760
  n(this, "apiClient");
@@ -756,7 +765,7 @@ const D = new N(), B = class B extends ae {
756
765
  return;
757
766
  const r = t.primaryAgentId || t.agents[0]?.agentId;
758
767
  if (r)
759
- return t.agents.find((o) => o.agentId === r);
768
+ return t.agents.find((s) => s.agentId === r);
760
769
  }));
761
770
  n(this, "currentOrg", Q(() => {
762
771
  const t = this.currentAgent.value;
@@ -764,7 +773,7 @@ const D = new N(), B = class B extends ae {
764
773
  return;
765
774
  const r = this.activeUser.value;
766
775
  if (r?.orgs)
767
- return r.orgs.find((o) => o.orgId === t.orgId);
776
+ return r.orgs.find((s) => s.orgId === t.orgId);
768
777
  }));
769
778
  // Initialization state
770
779
  n(this, "initialized");
@@ -775,20 +784,20 @@ const D = new N(), B = class B extends ae {
775
784
  n(this, "billing");
776
785
  n(this, "chat");
777
786
  n(this, "user");
778
- D.set(this), this.apiClient = ne(
787
+ D.set(this), this.apiClient = ce(
779
788
  { isDev: this.isDev, apiBase: this.apiBase },
780
789
  this.processApiResponse.bind(this),
781
790
  {
782
- getDeviceId: /* @__PURE__ */ d(() => this.deviceId.value, "getDeviceId"),
783
- onAccessTokenRefreshed: /* @__PURE__ */ d((s) => {
784
- this.token.value = s, this.persistAuth();
791
+ getDeviceId: /* @__PURE__ */ g(() => this.deviceId.value, "getDeviceId"),
792
+ onAccessTokenRefreshed: /* @__PURE__ */ g((o) => {
793
+ this.token.value = o, this.persistAuth();
785
794
  }, "onAccessTokenRefreshed"),
786
- onTerminalFailure: /* @__PURE__ */ d(() => {
795
+ onTerminalFailure: /* @__PURE__ */ g(() => {
787
796
  this.clearSession();
788
797
  }, "onTerminalFailure")
789
798
  }
790
799
  );
791
- const o = {
800
+ const s = {
792
801
  api: this.api,
793
802
  apiBase: this.apiBase,
794
803
  isDev: this.isDev,
@@ -802,12 +811,12 @@ const D = new N(), B = class B extends ae {
802
811
  logger: this.logger,
803
812
  processApiResponse: this.processApiResponse.bind(this)
804
813
  };
805
- this.agent = new _(o), this.auth = new j(o), this.billing = new F(o), this.chat = new C(o), this.user = new L(o), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((s) => {
806
- this.resolveUser = s;
807
- }), this.token.value && !this.activeUser.value ? this.getCurrentUser().then((s) => {
808
- this.resolveUser && (this.resolveUser(s), this.resolveUser = void 0);
809
- }).catch((s) => {
810
- this.logger.error("Auto user fetch failed", { data: s }), this.resolveUser && (this.resolveUser(void 0), this.resolveUser = void 0);
814
+ this.agent = new _(s), this.auth = new j(s), this.billing = new C(s), this.chat = new F(s), this.user = new L(s), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((o) => {
815
+ this.resolveUser = o;
816
+ }), this.token.value && !this.activeUser.value ? this.getCurrentUser().then((o) => {
817
+ this.resolveUser && (this.resolveUser(o), this.resolveUser = void 0);
818
+ }).catch((o) => {
819
+ this.logger.error("Auto user fetch failed", { data: o }), this.resolveUser && (this.resolveUser(void 0), this.resolveUser = void 0);
811
820
  }) : this.activeUser.value ? this.resolveUser?.(this.activeUser.value) : this.resolveUser?.(void 0);
812
821
  }
813
822
  /**
@@ -831,8 +840,8 @@ const D = new N(), B = class B extends ae {
831
840
  if (!t.ok) return;
832
841
  let r = !1;
833
842
  t.user && (this.activeUser.value = t.user, this.logger.info("User updated from API response", { data: t.user }), r = !0), t.token && (this.token.value = t.token, this.logger.info("Token updated from API response"), r = !0);
834
- const o = t.data?.deviceId;
835
- o && (this.deviceId.value = o, r = !0), r && this.persistAuth(), this.resolveUser && (this.resolveUser(t.user), this.resolveUser = void 0);
843
+ const s = t.data?.deviceId;
844
+ s && (this.deviceId.value = s, r = !0), r && this.persistAuth(), this.resolveUser && (this.resolveUser(t.user), this.resolveUser = void 0);
836
845
  }
837
846
  authRefs() {
838
847
  return {
@@ -850,7 +859,7 @@ const D = new N(), B = class B extends ae {
850
859
  }
851
860
  // Full reset - clears session + state + destroys singleton
852
861
  clear() {
853
- this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = O({ prefix: "ses" }), D.delete();
862
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = R({ prefix: "ses" }), D.delete();
854
863
  }
855
864
  // Backward-compatible delegates — these forward to sub-clients
856
865
  // Can be removed in a future breaking change
@@ -875,8 +884,8 @@ const D = new N(), B = class B extends ae {
875
884
  loginWithGoogle(t) {
876
885
  return this.auth.loginWithGoogle(t);
877
886
  }
878
- async chatStream(t) {
879
- return this.chat.chatStream(t);
887
+ async chatStreamPublic(t) {
888
+ return this.chat.chatStreamPublic(t);
880
889
  }
881
890
  async chatStreamAuthenticated(t) {
882
891
  return this.chat.chatStreamAuthenticated(t);
@@ -894,14 +903,14 @@ const D = new N(), B = class B extends ae {
894
903
  return this.user.track(t);
895
904
  }
896
905
  };
897
- d(B, "PageLinesSDK");
898
- let Y = B;
906
+ g(B, "PageLinesSDK");
907
+ let Z = B;
899
908
  export {
900
909
  _ as A,
901
- C,
902
- Y as P,
910
+ F as C,
911
+ Z as P,
903
912
  L as U,
904
913
  j as a,
905
- y as r
914
+ w as r
906
915
  };
907
916
  //# sourceMappingURL=sdkClient.js.map