@pagelines/sdk 1.0.603 → 1.0.605

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,15 +1,15 @@
1
- var se = Object.defineProperty;
2
- var pe = (a, e, t) => e in a ? se(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
- var d = (a, e) => se(a, "name", { value: e, configurable: !0 });
4
- var c = (a, e, t) => pe(a, typeof e != "symbol" ? e + "" : e, t);
5
- import { APP_PORT as me, APP_PROD_URL as ye, createRefreshingFetch as we, cookieUtil as U, createLogger as xe, shortId as Ie, zChatEvent as ke, objectId as N, SettingsObject as Se } from "@pagelines/core";
6
- import { watch as C, ref as O, computed as ae } from "vue";
7
- function k(a, e) {
8
- return a || (e ? `http://localhost:${me}` : ye);
1
+ var Q = Object.defineProperty;
2
+ var ee = (i, e, t) => e in i ? Q(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
+ var c = (i, e) => Q(i, "name", { value: e, configurable: !0 });
4
+ var l = (i, e, t) => ee(i, typeof e != "symbol" ? e + "" : e, t);
5
+ import { APP_PORT as te, APP_PROD_URL as re, createRefreshingFetch as oe, cookieUtil as S, createLogger as se, shortId as ie, runAuthenticatedChatTurnStream as ae, zChatEvent as ne, objectId as O, SettingsObject as ce } from "@pagelines/core";
6
+ import { watch as F, ref as b, computed as V } from "vue";
7
+ function p(i, e) {
8
+ return i || (e ? `http://localhost:${te}` : re);
9
9
  }
10
- d(k, "resolveApiBase");
11
- function be(a, e, t) {
12
- const r = k(a.apiBase, a.isDev), o = t ? we({
10
+ c(p, "resolveApiBase");
11
+ function le(i, e, t) {
12
+ const r = p(i.apiBase, i.isDev), o = t ? oe({
13
13
  fetch: globalThis.fetch.bind(globalThis),
14
14
  getDeviceId: t.getDeviceId,
15
15
  refreshUrl: `${r}/api/auth/refresh`,
@@ -17,55 +17,55 @@ function be(a, e, t) {
17
17
  onTerminalFailure: t.onTerminalFailure
18
18
  }) : globalThis.fetch.bind(globalThis);
19
19
  return async (s, n) => {
20
- const f = U.getAuthToken(), i = new Headers(n?.headers);
21
- i.has("Content-Type") || i.set("Content-Type", "application/json"), f && !i.has("Authorization") && i.set("Authorization", `Bearer ${f}`);
22
- const p = typeof s == "string" && s.startsWith("/") ? `${r}${s}` : s, g = await o(p, {
20
+ const d = S.getAuthToken(), a = new Headers(n?.headers);
21
+ a.has("Content-Type") || a.set("Content-Type", "application/json"), d && !a.has("Authorization") && a.set("Authorization", `Bearer ${d}`);
22
+ const g = typeof s == "string" && s.startsWith("/") ? `${r}${s}` : s, f = await o(g, {
23
23
  ...n,
24
- headers: i,
24
+ headers: a,
25
25
  credentials: "include"
26
26
  });
27
27
  if (e) {
28
- const w = g.json.bind(g);
29
- g.json = async () => {
30
- const l = await w();
31
- return typeof l == "object" && l !== null && "ok" in l && ("user" in l || "token" in l) && e(l), l;
28
+ const w = f.json.bind(f);
29
+ f.json = async () => {
30
+ const h = await w();
31
+ return typeof h == "object" && h !== null && "ok" in h && ("user" in h || "token" in h) && e(h), h;
32
32
  };
33
33
  }
34
- return g;
34
+ return f;
35
35
  };
36
36
  }
37
- d(be, "createApiFetch");
38
- const Te = /* @__PURE__ */ Symbol("clean");
39
- let y = [], b = 0;
40
- const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal = { epoch: 0 }), H = /* @__PURE__ */ d(/* @__NO_SIDE_EFFECTS__ */ (a) => {
37
+ c(le, "createApiFetch");
38
+ const ue = /* @__PURE__ */ Symbol("clean");
39
+ let v = [], y = 0;
40
+ const T = 4, he = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal = { epoch: 0 }), N = /* @__PURE__ */ c(/* @__NO_SIDE_EFFECTS__ */ (i) => {
41
41
  let e = [], t = {
42
42
  get() {
43
43
  return t.lc || t.listen(() => {
44
44
  })(), t.value;
45
45
  },
46
- init: a,
46
+ init: i,
47
47
  lc: 0,
48
48
  listen(r) {
49
49
  return t.lc = e.push(r), () => {
50
- for (let s = b + P; s < y.length; )
51
- y[s] === r ? y.splice(s, P) : s += P;
50
+ for (let s = y + T; s < v.length; )
51
+ v[s] === r ? v.splice(s, T) : s += T;
52
52
  let o = e.indexOf(r);
53
53
  ~o && (e.splice(o, 1), --t.lc || t.off());
54
54
  };
55
55
  },
56
56
  notify(r, o) {
57
- Ee.epoch++;
58
- let s = !y.length;
57
+ he.epoch++;
58
+ let s = !v.length;
59
59
  for (let n of e)
60
- y.push(n, t.value, r, o);
60
+ v.push(n, t.value, r, o);
61
61
  if (s) {
62
- for (b = 0; b < y.length; b += P)
63
- y[b](
64
- y[b + 1],
65
- y[b + 2],
66
- y[b + 3]
62
+ for (y = 0; y < v.length; y += T)
63
+ v[y](
64
+ v[y + 1],
65
+ v[y + 2],
66
+ v[y + 3]
67
67
  );
68
- y.length = 0;
68
+ v.length = 0;
69
69
  }
70
70
  },
71
71
  /* It will be called on last listener unsubscribing.
@@ -80,14 +80,14 @@ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
80
80
  let o = t.listen(r);
81
81
  return r(t.value), o;
82
82
  },
83
- value: a
83
+ value: i
84
84
  };
85
- return process.env.NODE_ENV !== "production" && (t[Te] = () => {
85
+ return process.env.NODE_ENV !== "production" && (t[ue] = () => {
86
86
  e = [], t.lc = 0, t.off();
87
87
  }), t;
88
- }, "atom"), S = globalThis, D = S.__PL_AUTH_USER__ ?? (S.__PL_AUTH_USER__ = /* @__PURE__ */ H(void 0)), B = S.__PL_AUTH_TOKEN__ ?? (S.__PL_AUTH_TOKEN__ = /* @__PURE__ */ H(null)), L = S.__PL_AUTH_DEVICE_ID__ ?? (S.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ H(null)), Q = class Q {
88
+ }, "atom"), m = globalThis, U = m.__PL_AUTH_USER__ ?? (m.__PL_AUTH_USER__ = /* @__PURE__ */ N(void 0)), E = m.__PL_AUTH_TOKEN__ ?? (m.__PL_AUTH_TOKEN__ = /* @__PURE__ */ N(null)), A = m.__PL_AUTH_DEVICE_ID__ ?? (m.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ N(null)), z = class z {
89
89
  constructor() {
90
- c(this, "logger", xe("SDKStorage"));
90
+ l(this, "logger", se("SDKStorage"));
91
91
  }
92
92
  /**
93
93
  * Check if localStorage is fully functional (some test environments provide partial mocks)
@@ -99,13 +99,13 @@ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
99
99
  * Sync Vue reactive refs with global nanostores for cross-bundle persistence.
100
100
  */
101
101
  syncWithGlobalStores(e) {
102
- const { activeUser: t, token: r, deviceId: o } = e, s = D.get(), n = B.get(), f = L.get();
103
- s && (t.value = s), n && (r.value = n), f && (o.value = f), C(t, (i) => D.set(i), { immediate: !0 }), C(r, (i) => B.set(i), { immediate: !0 }), C(o, (i) => L.set(i), { immediate: !0 }), D.subscribe((i) => {
104
- i !== t.value && (t.value = i);
105
- }), B.subscribe((i) => {
106
- i !== r.value && (r.value = i);
107
- }), L.subscribe((i) => {
108
- i !== o.value && (o.value = i);
102
+ const { activeUser: t, token: r, deviceId: o } = e, s = U.get(), n = E.get(), d = A.get();
103
+ s && (t.value = s), n && (r.value = n), d && (o.value = d), F(t, (a) => U.set(a), { immediate: !0 }), F(r, (a) => E.set(a), { immediate: !0 }), F(o, (a) => A.set(a), { immediate: !0 }), U.subscribe((a) => {
104
+ a !== t.value && (t.value = a);
105
+ }), E.subscribe((a) => {
106
+ a !== r.value && (r.value = a);
107
+ }), A.subscribe((a) => {
108
+ a !== o.value && (o.value = a);
109
109
  });
110
110
  }
111
111
  /**
@@ -115,9 +115,9 @@ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
115
115
  loadFromStorage(e) {
116
116
  if (typeof window > "u")
117
117
  return;
118
- const t = U.getAuthToken();
118
+ const t = S.getAuthToken();
119
119
  t && (e.token.value = t);
120
- const r = U.getDeviceId();
120
+ const r = S.getDeviceId();
121
121
  if (r && (e.deviceId.value = r), this.isLocalStorageFunctional())
122
122
  try {
123
123
  const o = localStorage.getItem("pagelines-user");
@@ -131,7 +131,7 @@ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
131
131
  * deviceId is server-owned (Set-Cookie) — JS doesn't write it.
132
132
  */
133
133
  saveToStorage(e) {
134
- if (!(typeof window > "u") && (e.token.value ? U.setAuthToken(e.token.value) : U.removeAuthToken(), this.isLocalStorageFunctional()))
134
+ if (!(typeof window > "u") && (e.token.value ? S.setAuthToken(e.token.value) : S.removeAuthToken(), this.isLocalStorageFunctional()))
135
135
  try {
136
136
  e.activeUser.value ? localStorage.setItem("pagelines-user", JSON.stringify(e.activeUser.value)) : localStorage.removeItem("pagelines-user");
137
137
  } catch (t) {
@@ -145,13 +145,13 @@ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
145
145
  */
146
146
  clearStorage() {
147
147
  if (!(typeof window > "u")) {
148
- if (U.removeAuthToken(), this.isLocalStorageFunctional())
148
+ if (S.removeAuthToken(), this.isLocalStorageFunctional())
149
149
  try {
150
150
  localStorage.removeItem("pagelines-user");
151
151
  } catch (e) {
152
152
  this.logger.error("Failed to clear user from localStorage", { data: e });
153
153
  }
154
- D.set(void 0), B.set(null), L.set(null);
154
+ U.set(void 0), E.set(null), A.set(null);
155
155
  }
156
156
  }
157
157
  /**
@@ -178,15 +178,15 @@ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
178
178
  }
179
179
  }
180
180
  };
181
- d(Q, "SDKStorage");
182
- let J = Q;
183
- const V = class V {
181
+ c(z, "SDKStorage");
182
+ let B = z;
183
+ const J = class J {
184
184
  constructor(e) {
185
- c(this, "ctx");
185
+ l(this, "ctx");
186
186
  this.ctx = e;
187
187
  }
188
188
  async create(e) {
189
- const t = e.orgId || this.resolveOrgId(), r = k(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/agents`, {
189
+ const t = e.orgId || this.resolveOrgId(), r = p(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/agents`, {
190
190
  method: "POST",
191
191
  headers: {
192
192
  "Content-Type": "application/json",
@@ -207,7 +207,7 @@ const V = class V {
207
207
  * `{ lifecycle: 'unknown' }` is the graceful degrade on any fetch failure.
208
208
  */
209
209
  async getLiveStatus(e) {
210
- const t = k(this.ctx.apiBase, this.ctx.isDev);
210
+ const t = p(this.ctx.apiBase, this.ctx.isDev);
211
211
  try {
212
212
  const o = await (await fetch(`${t}/api/agents/state?ids=${encodeURIComponent(e.agentId)}`, {
213
213
  headers: {
@@ -231,22 +231,22 @@ const V = class V {
231
231
  */
232
232
  async waitUntilReady(e) {
233
233
  const { agentId: t, onStatus: r, timeoutMs: o = 3e5, pollIntervalMs: s = 3e3 } = e, n = Date.now();
234
- let f;
234
+ let d;
235
235
  for (; Date.now() - n < o; ) {
236
- const i = await this.getLiveStatus({ agentId: t });
237
- if (i.lifecycle === "running") {
236
+ const a = await this.getLiveStatus({ agentId: t });
237
+ if (a.lifecycle === "running") {
238
238
  r?.("running");
239
239
  return;
240
240
  }
241
- if (i.lifecycle === "error")
242
- throw new Error(i.detail || "Your assistant hit a problem starting");
243
- i.lifecycle !== f && (r?.(i.lifecycle), f = i.lifecycle), await new Promise((p) => setTimeout(p, s));
241
+ if (a.lifecycle === "error")
242
+ throw new Error(a.detail || "Your assistant hit a problem starting");
243
+ a.lifecycle !== d && (r?.(a.lifecycle), d = a.lifecycle), await new Promise((g) => setTimeout(g, s));
244
244
  }
245
245
  throw new Error("Your assistant is taking longer than expected — please try again");
246
246
  }
247
247
  /** Send a typed webhook event to a bot agent. No auth required — the proxy is public. */
248
248
  async webhook(e) {
249
- const r = `${k(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/webhooks/agents/${e.agentId}`, o = { type: e.type, data: e.data };
249
+ const r = `${p(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/webhooks/agents/${e.agentId}`, o = { type: e.type, data: e.data };
250
250
  e.meta && (o.meta = e.meta);
251
251
  const s = await fetch(r, {
252
252
  method: "POST",
@@ -266,24 +266,24 @@ const V = class V {
266
266
  return t;
267
267
  }
268
268
  };
269
- d(V, "AgentClient");
270
- let z = V;
271
- async function E(a, e) {
272
- a.loading.value = !0, a.error.value = null;
269
+ c(J, "AgentClient");
270
+ let P = J;
271
+ async function k(i, e) {
272
+ i.loading.value = !0, i.error.value = null;
273
273
  try {
274
274
  return await e();
275
275
  } finally {
276
- a.loading.value = !1;
276
+ i.loading.value = !1;
277
277
  }
278
278
  }
279
- d(E, "withLoadingState");
280
- const Y = class Y {
279
+ c(k, "withLoadingState");
280
+ const W = class W {
281
281
  constructor(e) {
282
- c(this, "ctx");
282
+ l(this, "ctx");
283
283
  this.ctx = e;
284
284
  }
285
285
  async sendCode(e) {
286
- return E(this.ctx, async () => {
286
+ return k(this.ctx, async () => {
287
287
  try {
288
288
  const r = await (await this.ctx.apiFetch("/api/auth/check-email", {
289
289
  method: "POST",
@@ -299,7 +299,7 @@ const Y = class Y {
299
299
  });
300
300
  }
301
301
  async verifyCode(e, t) {
302
- return E(this.ctx, async () => {
302
+ return k(this.ctx, async () => {
303
303
  try {
304
304
  const o = await (await this.ctx.apiFetch("/api/auth/verify-code", {
305
305
  method: "POST",
@@ -315,7 +315,7 @@ const Y = class Y {
315
315
  });
316
316
  }
317
317
  async logout() {
318
- return E(this.ctx, async () => {
318
+ return k(this.ctx, async () => {
319
319
  try {
320
320
  await this.ctx.apiFetch("/api/auth/logout", { method: "POST" });
321
321
  } catch (e) {
@@ -326,7 +326,7 @@ const Y = class Y {
326
326
  }
327
327
  async getCurrentUser() {
328
328
  if (this.ctx.token.value)
329
- return E(this.ctx, async () => {
329
+ return k(this.ctx, async () => {
330
330
  try {
331
331
  const t = await (await this.ctx.apiFetch("/api/users/me", {
332
332
  method: "GET"
@@ -343,7 +343,7 @@ const Y = class Y {
343
343
  });
344
344
  }
345
345
  async requestAuthCode(e) {
346
- return E(this.ctx, async () => {
346
+ return k(this.ctx, async () => {
347
347
  try {
348
348
  const r = await (await this.ctx.apiFetch("/api/auth/check-email", {
349
349
  method: "POST",
@@ -356,7 +356,7 @@ const Y = class Y {
356
356
  });
357
357
  }
358
358
  async loginWithCode(e) {
359
- return E(this.ctx, async () => {
359
+ return k(this.ctx, async () => {
360
360
  try {
361
361
  const r = await (await this.ctx.apiFetch("/api/auth/verify-code", {
362
362
  method: "POST",
@@ -373,45 +373,45 @@ const Y = class Y {
373
373
  this.ctx.logger.error("loginWithGoogle: Only available in browser");
374
374
  return;
375
375
  }
376
- const t = k(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, o = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, s = 500, n = 600, f = window.screenX + (window.outerWidth - s) / 2, i = window.screenY + (window.outerHeight - n) / 2, p = window.open(
376
+ const t = p(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, o = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, s = 500, n = 600, d = window.screenX + (window.outerWidth - s) / 2, a = window.screenY + (window.outerHeight - n) / 2, g = window.open(
377
377
  o,
378
378
  "google-auth",
379
- `width=${s},height=${n},left=${f},top=${i},popup=yes`
379
+ `width=${s},height=${n},left=${d},top=${a},popup=yes`
380
380
  );
381
- if (!p) {
382
- const l = "Popup was blocked. Please allow popups for this site.";
383
- this.ctx.error.value = l, e?.onError?.(l);
381
+ if (!g) {
382
+ const h = "Popup was blocked. Please allow popups for this site.";
383
+ this.ctx.error.value = h, e?.onError?.(h);
384
384
  return;
385
385
  }
386
- const g = /* @__PURE__ */ d((l) => {
387
- const m = new URL(t).origin;
388
- if (l.origin === m) {
389
- if (l.data?.type === "auth-success") {
390
- window.removeEventListener("message", g);
391
- const { token: x, user: h } = l.data;
392
- this.ctx.processApiResponse({ ok: !0, data: {}, token: x, user: h }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(h);
393
- } else if (l.data?.type === "auth-error") {
394
- window.removeEventListener("message", g);
395
- const x = l.data.error || "Google authentication failed";
386
+ const f = /* @__PURE__ */ c((h) => {
387
+ const I = new URL(t).origin;
388
+ if (h.origin === I) {
389
+ if (h.data?.type === "auth-success") {
390
+ window.removeEventListener("message", f);
391
+ const { token: x, user: u } = h.data;
392
+ this.ctx.processApiResponse({ ok: !0, data: {}, token: x, user: u }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(u);
393
+ } else if (h.data?.type === "auth-error") {
394
+ window.removeEventListener("message", f);
395
+ const x = h.data.error || "Google authentication failed";
396
396
  this.ctx.error.value = x, this.ctx.logger.error("Google login failed", { error: x }), e?.onError?.(x);
397
397
  }
398
398
  }
399
399
  }, "handler");
400
- window.addEventListener("message", g);
400
+ window.addEventListener("message", f);
401
401
  const w = setInterval(() => {
402
- p.closed && (clearInterval(w), window.removeEventListener("message", g));
402
+ g.closed && (clearInterval(w), window.removeEventListener("message", f));
403
403
  }, 500);
404
404
  }
405
405
  };
406
- d(Y, "AuthClient");
407
- let G = Y;
408
- const X = class X {
406
+ c(W, "AuthClient");
407
+ let R = W;
408
+ const G = class G {
409
409
  constructor(e) {
410
- c(this, "ctx");
410
+ l(this, "ctx");
411
411
  this.ctx = e;
412
412
  }
413
413
  async startTrial(e) {
414
- const t = this.resolveOrgId(), r = k(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/billing/checkout/create`, {
414
+ const t = this.resolveOrgId(), r = p(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/billing/checkout/create`, {
415
415
  method: "POST",
416
416
  headers: {
417
417
  "Content-Type": "application/json",
@@ -433,7 +433,7 @@ const X = class X {
433
433
  return this.getStatus();
434
434
  }
435
435
  async getStatus() {
436
- const e = this.resolveOrgId(), t = k(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/billing/details/${e}`, {
436
+ const e = this.resolveOrgId(), t = p(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/billing/details/${e}`, {
437
437
  headers: {
438
438
  ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
439
439
  }
@@ -462,10 +462,10 @@ const X = class X {
462
462
  return t;
463
463
  }
464
464
  };
465
- d(X, "BillingClient");
466
- let q = X;
467
- function ie(a) {
468
- const e = a.split(`
465
+ c(G, "BillingClient");
466
+ let L = G;
467
+ function de(i) {
468
+ const e = i.split(`
469
469
  `).filter((o) => o.length > 0);
470
470
  let t, r;
471
471
  for (const o of e)
@@ -473,44 +473,58 @@ function ie(a) {
473
473
  if (!t || r === void 0)
474
474
  return null;
475
475
  try {
476
- const o = ke.safeParse({ event: t, data: JSON.parse(r) });
476
+ const o = ne.safeParse({ event: t, data: JSON.parse(r) });
477
477
  return o.success ? o.data : null;
478
478
  } catch {
479
479
  return null;
480
480
  }
481
481
  }
482
- d(ie, "parseChatEvent");
483
- function ne(a) {
482
+ c(de, "parseChatEvent");
483
+ function Y(i) {
484
484
  return {
485
- code: a.code,
486
- error: a.message,
487
- ...a.bucket ? { bucket: a.bucket } : {},
488
- ...a.actionLabel ? { actionLabel: a.actionLabel } : {},
489
- ...a.actionUrl ? { actionUrl: a.actionUrl } : {},
490
- ...a.help ? { help: a.help } : {}
485
+ code: i.code,
486
+ error: i.message,
487
+ ...i.bucket ? { bucket: i.bucket } : {},
488
+ ...i.actionLabel ? { actionLabel: i.actionLabel } : {},
489
+ ...i.actionUrl ? { actionUrl: i.actionUrl } : {},
490
+ ...i.help ? { help: i.help } : {}
491
491
  };
492
492
  }
493
- d(ne, "toChatStreamError");
494
- function ce(a) {
495
- if (!(a.role !== "assistant" && a.role !== "system"))
493
+ c(Y, "toChatStreamError");
494
+ function ge(i) {
495
+ return i.stage === "stream-open" && i.message.startsWith("HTTP ") ? `Stream failed: ${i.message}` : i.message;
496
+ }
497
+ c(ge, "toAuthenticatedTransportError");
498
+ function X(i) {
499
+ if (!(i.role !== "assistant" && i.role !== "system"))
496
500
  return {
497
- id: a.messageId,
498
- text: a.content,
499
- sender: a.role === "system" ? "system" : "agent",
500
- timestamp: a.createdAt,
501
- conversationId: a.conversationId,
502
- sequence: a.sequence,
503
- systemKind: a.systemKind,
504
- ...a.metadata?.attachments?.length ? { attachments: a.metadata.attachments } : {},
505
- ...a.metadata?.issue ? { issue: a.metadata.issue } : {}
501
+ id: i.messageId,
502
+ text: i.content,
503
+ sender: i.role === "system" ? "system" : "agent",
504
+ timestamp: i.createdAt,
505
+ conversationId: i.conversationId,
506
+ sequence: i.sequence,
507
+ systemKind: i.systemKind,
508
+ ...i.metadata?.attachments?.length ? { attachments: i.metadata.attachments } : {},
509
+ ...i.metadata?.issue ? { issue: i.metadata.issue } : {}
506
510
  };
507
511
  }
508
- d(ce, "toChatMessage");
509
- const Z = class Z {
512
+ c(X, "toChatMessage");
513
+ const q = class q {
510
514
  constructor(e) {
511
- c(this, "ctx");
515
+ l(this, "ctx");
512
516
  this.ctx = e;
513
517
  }
518
+ async cancelConversationTurn(e) {
519
+ const t = p(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {}, o = await fetch(`${t}/api/conversations/${encodeURIComponent(e.conversationId)}/cancel`, {
520
+ method: "POST",
521
+ headers: { "Content-Type": "application/json", ...r },
522
+ body: JSON.stringify(e.turnId ? { turnId: e.turnId } : {})
523
+ }), s = await o.json();
524
+ if (!s.ok)
525
+ throw new Error(s.error || `Cancel failed: HTTP ${o.status}`);
526
+ return s.data;
527
+ }
514
528
  /**
515
529
  * Public/visitor chat — anonymous chat against an agent's public handle,
516
530
  * routed through the messaging substrate. Same SSE wire format as
@@ -522,10 +536,10 @@ const Z = class Z {
522
536
  * which stores a stable ID in localStorage).
523
537
  */
524
538
  async chatStreamPublic(e) {
525
- const r = `${k(this.ctx.apiBase, this.ctx.isDev)}/api/agents/public/${encodeURIComponent(e.handle)}/chat/v2/stream`;
526
- let o = "", s = !1, n = !1, f;
539
+ const r = `${p(this.ctx.apiBase, this.ctx.isDev)}/api/agents/public/${encodeURIComponent(e.handle)}/chat/v2/stream`;
540
+ let o = "", s = !1, n = !1, d;
527
541
  try {
528
- const i = await fetch(r, {
542
+ const a = await fetch(r, {
529
543
  method: "POST",
530
544
  headers: { "Content-Type": "application/json" },
531
545
  body: JSON.stringify({
@@ -535,57 +549,59 @@ const Z = class Z {
535
549
  ...e.context ? { context: e.context } : {}
536
550
  })
537
551
  });
538
- if (!i.ok) {
539
- const w = await i.json().catch(() => ({ error: "Request failed" }));
540
- e.onError(w.error || `HTTP ${i.status}`);
552
+ if (!a.ok) {
553
+ const w = await a.json().catch(() => ({ error: "Request failed" }));
554
+ e.onError(w.error || `HTTP ${a.status}`);
541
555
  return;
542
556
  }
543
- if (o = i.headers.get("X-Conversation-Id") || "", f = i.body?.getReader(), !f) {
557
+ if (o = a.headers.get("X-Conversation-Id") || "", d = a.body?.getReader(), !d) {
544
558
  e.onError("No response stream");
545
559
  return;
546
560
  }
547
- const p = new TextDecoder();
548
- let g = "";
561
+ const g = new TextDecoder();
562
+ let f = "";
549
563
  e: for (; ; ) {
550
- const { done: w, value: l } = await f.read();
564
+ const { done: w, value: h } = await d.read();
551
565
  if (w)
552
566
  break;
553
- g += p.decode(l, { stream: !0 });
554
- let m = g.indexOf(`
567
+ f += g.decode(h, { stream: !0 });
568
+ let I = f.indexOf(`
555
569
 
556
570
  `);
557
- for (; m !== -1; ) {
558
- const x = g.slice(0, m);
559
- g = g.slice(m + 2);
560
- const h = ie(x);
561
- if (h) {
562
- if (h.event === "working_state")
563
- e.onStatus?.(h.data.description);
564
- else if (h.event === "working_end")
571
+ for (; I !== -1; ) {
572
+ const x = f.slice(0, I);
573
+ f = f.slice(I + 2);
574
+ const u = de(x);
575
+ if (u) {
576
+ if (u.event === "working_state")
577
+ e.onStatus?.(u.data.description);
578
+ else if (u.event === "tool_activity")
579
+ e.onToolActivity?.(u.data);
580
+ else if (u.event === "working_end")
565
581
  e.onWorkingEnd?.();
566
- else if (h.event === "message_delta")
567
- e.onDelta(h.data.delta, h.data.role);
568
- else if (h.event === "error") {
569
- s = !0, e.onError(ne(h.data));
582
+ else if (u.event === "message_delta")
583
+ e.onDelta(u.data.delta, u.data.role);
584
+ else if (u.event === "error") {
585
+ s = !0, e.onError(Y(u.data));
570
586
  break e;
571
- } else if (h.event === "message" && (h.data.message.role === "assistant" || h.data.message.role === "system")) {
587
+ } else if (u.event === "message" && (u.data.message.role === "assistant" || u.data.message.role === "system")) {
572
588
  n = !0;
573
- const A = ce(h.data.message);
574
- A && e.onMessage?.(A);
575
- } else if (h.event === "stream_end")
589
+ const H = X(u.data.message);
590
+ H && e.onMessage?.(H);
591
+ } else if (u.event === "stream_end")
576
592
  break e;
577
593
  }
578
- m = g.indexOf(`
594
+ I = f.indexOf(`
579
595
 
580
596
  `);
581
597
  }
582
598
  }
583
599
  !s && n ? e.onDone(o) : s || e.onError("Stream ended before reply arrived");
584
- } catch (i) {
585
- e.onError(i instanceof Error ? i.message : "Stream failed");
600
+ } catch (a) {
601
+ e.onError(a instanceof Error ? a.message : "Stream failed");
586
602
  } finally {
587
603
  try {
588
- await f?.cancel();
604
+ await d?.cancel();
589
605
  } catch {
590
606
  }
591
607
  }
@@ -599,140 +615,53 @@ const Z = class Z {
599
615
  * Mirrors `src/modules/agent/client.ts → sendChatMessageStream`.
600
616
  */
601
617
  async chatStreamAuthenticated(e) {
602
- const t = k(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {};
618
+ const t = p(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {};
603
619
  let o, s = null;
604
620
  try {
605
- const u = await fetch(`${t}/api/conversations`, {
621
+ const a = await fetch(`${t}/api/conversations`, {
606
622
  method: "POST",
607
623
  headers: { "Content-Type": "application/json", ...r },
608
624
  body: JSON.stringify({ agentId: e.agentId })
609
- }), I = await u.json();
610
- if (!I.ok) {
611
- e.onError(I.error || `Conversation failed: HTTP ${u.status}`);
625
+ }), g = await a.json();
626
+ if (!g.ok) {
627
+ e.onError(g.error || `Conversation failed: HTTP ${a.status}`);
612
628
  return;
613
629
  }
614
- o = I.data.conversationId, s = I.data.latestSequence ?? null;
615
- } catch (u) {
616
- e.onError(u instanceof Error ? u.message : "Conversation failed");
630
+ o = g.data.conversationId, s = g.data.latestSequence ?? null;
631
+ } catch (a) {
632
+ e.onError(a instanceof Error ? a.message : "Conversation failed");
617
633
  return;
618
634
  }
619
- let n = !1, f = !1, i = !1, p = !1, g = !1, w = !1, l;
620
- const m = new AbortController();
621
- let x = !1, h, A = /* @__PURE__ */ d(() => {
622
- }, "resolveStreamReady");
623
- const de = new Promise((u) => {
624
- A = u;
625
- }), $ = /* @__PURE__ */ d((u) => {
626
- x || (x = !0, h && clearTimeout(h), A(u));
627
- }, "settleStreamReady"), re = /* @__PURE__ */ d(() => {
628
- l?.cancel().catch(() => {
629
- });
630
- }, "cancelReader"), ue = s ? `${t}/api/conversations/${encodeURIComponent(o)}/stream?since=${encodeURIComponent(s)}` : `${t}/api/conversations/${encodeURIComponent(o)}/stream`;
631
- h = setTimeout(() => {
632
- w = !0, i = !0, e.onError("Timed out opening stream"), m.abort(), $("failed");
633
- }, 1e4);
634
- const R = (async () => {
635
- try {
636
- const u = await fetch(ue, {
637
- headers: r,
638
- signal: m.signal
639
- });
640
- if (!u.ok) {
641
- i = !0, $("failed"), e.onError(`Stream failed: HTTP ${u.status}`);
642
- return;
643
- }
644
- if (l = u.body?.getReader(), !l) {
645
- i = !0, $("failed"), e.onError("No response stream");
646
- return;
647
- }
648
- $("ready");
649
- const I = new TextDecoder();
650
- let T = "";
651
- e: for (; ; ) {
652
- const { done: fe, value: ge } = await l.read();
653
- if (fe)
654
- break;
655
- T += I.decode(ge, { stream: !0 });
656
- let F = T.indexOf(`
657
-
658
- `);
659
- for (; F !== -1; ) {
660
- const ve = T.slice(0, F);
661
- T = T.slice(F + 2);
662
- const v = ie(ve);
663
- if (v) {
664
- if (v.event === "working_state")
665
- n && e.onStatus?.(v.data.description);
666
- else if (v.event === "working_end")
667
- n && e.onWorkingEnd?.();
668
- else if (v.event === "message_delta")
669
- n && e.onDelta(v.data.delta, v.data.role);
670
- else if (v.event === "error") {
671
- i = !0, e.onError(ne(v.data));
672
- break e;
673
- } else if (v.event === "message" && (v.data.message.role === "assistant" || v.data.message.role === "system")) {
674
- if (!n)
675
- continue;
676
- p = !0;
677
- const oe = ce(v.data.message);
678
- oe && e.onMessage?.(oe);
679
- break e;
680
- } else if (v.event === "stream_end")
681
- break e;
682
- }
683
- F = T.indexOf(`
684
-
685
- `);
686
- }
687
- }
688
- !i && p ? e.onDone(o) : !i && n && !f && e.onError("Stream ended before reply arrived");
689
- } catch (u) {
690
- !f && !w && (i = !0, $("failed"), e.onError(u instanceof Error ? u.message : "Stream failed"));
691
- } finally {
692
- g = !0;
693
- try {
694
- await l?.cancel();
695
- } catch {
696
- }
697
- }
698
- })();
699
- if (await de === "failed") {
700
- await R;
701
- return;
702
- }
703
- if (g) {
704
- e.onError("Stream closed before send"), await R;
705
- return;
706
- }
707
- const he = `nonce_${Ie(16)}`;
708
- try {
709
- n = !0;
710
- const u = await fetch(`${t}/api/messages`, {
711
- method: "POST",
712
- headers: { "Content-Type": "application/json", ...r },
713
- body: JSON.stringify({
714
- conversationId: o,
715
- content: e.message,
716
- clientNonce: he,
717
- ...e.attachments && e.attachments.length > 0 ? { attachments: e.attachments } : {}
718
- })
719
- }), I = await u.json();
720
- if (!I.ok) {
721
- f = !0, m.abort(), re(), e.onError(I.error || `Send failed: HTTP ${u.status}`), await R;
722
- return;
723
- }
724
- } catch (u) {
725
- f = !0, m.abort(), re(), e.onError(u instanceof Error ? u.message : "Send failed"), await R;
726
- return;
727
- }
728
- await R;
635
+ const n = s ? `${t}/api/conversations/${encodeURIComponent(o)}/stream?since=${encodeURIComponent(s)}` : `${t}/api/conversations/${encodeURIComponent(o)}/stream`, d = `nonce_${ie(16)}`;
636
+ await ae({
637
+ streamUrl: n,
638
+ sendUrl: `${t}/api/messages`,
639
+ headers: r,
640
+ sendBody: {
641
+ conversationId: o,
642
+ content: e.message,
643
+ clientNonce: d,
644
+ ...e.attachments && e.attachments.length > 0 ? { attachments: e.attachments } : {}
645
+ },
646
+ onStatus: e.onStatus,
647
+ onDelta: e.onDelta,
648
+ onToolActivity: e.onToolActivity,
649
+ onWorkingEnd: e.onWorkingEnd,
650
+ onMessage: /* @__PURE__ */ c((a) => {
651
+ const g = X(a);
652
+ g && e.onMessage?.(g);
653
+ }, "onMessage"),
654
+ onDone: /* @__PURE__ */ c(() => e.onDone(o), "onDone"),
655
+ onChatError: /* @__PURE__ */ c((a) => e.onError(Y(a)), "onChatError"),
656
+ onTransportError: /* @__PURE__ */ c((a) => e.onError(ge(a)), "onTransportError")
657
+ });
729
658
  }
730
659
  };
731
- d(Z, "ChatClient");
732
- let W = Z;
733
- const ee = class ee {
660
+ c(q, "ChatClient");
661
+ let C = q;
662
+ const M = class M {
734
663
  constructor(e) {
735
- c(this, "ctx");
664
+ l(this, "ctx");
736
665
  this.ctx = e;
737
666
  }
738
667
  async getPublicAgent(e) {
@@ -770,7 +699,7 @@ const ee = class ee {
770
699
  generateAnonId() {
771
700
  const e = "pagelinesAnonId";
772
701
  let t = this.ctx.storage.getItem(e);
773
- return t || (t = N({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
702
+ return t || (t = O({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
774
703
  }
775
704
  track(e) {
776
705
  try {
@@ -785,11 +714,11 @@ const ee = class ee {
785
714
  }
786
715
  }
787
716
  };
788
- d(ee, "UserClient");
789
- let M = ee;
790
- const te = class te {
717
+ c(M, "UserClient");
718
+ let j = M;
719
+ const K = class K {
791
720
  constructor() {
792
- c(this, "key", "__PAGELINES_SDK__");
721
+ l(this, "key", "__PAGELINES_SDK__");
793
722
  }
794
723
  get() {
795
724
  if (!(typeof window > "u"))
@@ -802,30 +731,30 @@ const te = class te {
802
731
  typeof window < "u" && delete globalThis[this.key];
803
732
  }
804
733
  };
805
- d(te, "SDKGlobal");
806
- let K = te;
807
- const _ = new K(), j = class j extends Se {
734
+ c(K, "SDKGlobal");
735
+ let _ = K;
736
+ const $ = new _(), D = class D extends ce {
808
737
  constructor(t = {}) {
809
- const r = _.get();
738
+ const r = $.get();
810
739
  if (r)
811
740
  return console.debug("[PageLinesSDK] Returning existing singleton instance"), r;
812
741
  super("PageLinesSDK", t);
813
742
  // Vue reactive state
814
- c(this, "activeUser", O());
815
- c(this, "token", O(null));
743
+ l(this, "activeUser", b());
744
+ l(this, "token", b(null));
816
745
  // Refresh credential lives in HttpOnly pl-refresh-token cookie — JS never
817
746
  // holds it, so no reactive ref. /api/auth/refresh reads the cookie via the
818
747
  // browser's automatic credentials: 'include' attach.
819
- c(this, "deviceId", O(null));
820
- c(this, "loading", O(!1));
821
- c(this, "error", O(null));
822
- c(this, "apiBase", this.settings.apiBase || void 0);
748
+ l(this, "deviceId", b(null));
749
+ l(this, "loading", b(!1));
750
+ l(this, "error", b(null));
751
+ l(this, "apiBase", this.settings.apiBase || void 0);
823
752
  // Storage handler for persistence
824
- c(this, "storage", new J());
753
+ l(this, "storage", new B());
825
754
  // Auto-managed session ID for usage tracking
826
- c(this, "sessionId", N({ prefix: "ses" }));
755
+ l(this, "sessionId", O({ prefix: "ses" }));
827
756
  // Computed properties derived from activeUser (matches UserClient pattern)
828
- c(this, "currentAgent", ae(() => {
757
+ l(this, "currentAgent", V(() => {
829
758
  const t = this.activeUser.value;
830
759
  if (!t?.agents)
831
760
  return;
@@ -833,7 +762,7 @@ const _ = new K(), j = class j extends Se {
833
762
  if (r)
834
763
  return t.agents.find((o) => o.agentId === r);
835
764
  }));
836
- c(this, "currentOrg", ae(() => {
765
+ l(this, "currentOrg", V(() => {
837
766
  const t = this.currentAgent.value;
838
767
  if (!t?.orgId)
839
768
  return;
@@ -842,25 +771,25 @@ const _ = new K(), j = class j extends Se {
842
771
  return r.orgs.find((o) => o.orgId === t.orgId);
843
772
  }));
844
773
  // Initialization state
845
- c(this, "initialized");
846
- c(this, "resolveUser");
774
+ l(this, "initialized");
775
+ l(this, "resolveUser");
847
776
  // Sub-clients (new preferred API surface)
848
- c(this, "agent");
849
- c(this, "auth");
850
- c(this, "billing");
851
- c(this, "chat");
852
- c(this, "user");
853
- _.set(this);
777
+ l(this, "agent");
778
+ l(this, "auth");
779
+ l(this, "billing");
780
+ l(this, "chat");
781
+ l(this, "user");
782
+ $.set(this);
854
783
  const s = {
855
- apiFetch: be(
784
+ apiFetch: le(
856
785
  { isDev: this.isDev, apiBase: this.apiBase },
857
786
  this.processApiResponse.bind(this),
858
787
  {
859
- getDeviceId: /* @__PURE__ */ d(() => this.deviceId.value, "getDeviceId"),
860
- onAccessTokenRefreshed: /* @__PURE__ */ d((n) => {
788
+ getDeviceId: /* @__PURE__ */ c(() => this.deviceId.value, "getDeviceId"),
789
+ onAccessTokenRefreshed: /* @__PURE__ */ c((n) => {
861
790
  this.token.value = n, this.persistAuth();
862
791
  }, "onAccessTokenRefreshed"),
863
- onTerminalFailure: /* @__PURE__ */ d(() => {
792
+ onTerminalFailure: /* @__PURE__ */ c(() => {
864
793
  this.clearSession();
865
794
  }, "onTerminalFailure")
866
795
  }
@@ -877,7 +806,7 @@ const _ = new K(), j = class j extends Se {
877
806
  logger: this.logger,
878
807
  processApiResponse: this.processApiResponse.bind(this)
879
808
  };
880
- this.agent = new z(s), this.auth = new G(s), this.billing = new q(s), this.chat = new W(s), this.user = new M(s), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((n) => {
809
+ this.agent = new P(s), this.auth = new R(s), this.billing = new L(s), this.chat = new C(s), this.user = new j(s), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((n) => {
881
810
  this.resolveUser = n;
882
811
  }), this.token.value && !this.activeUser.value ? this.auth.getCurrentUser().then((n) => {
883
812
  this.resolveUser && (this.resolveUser(n), this.resolveUser = void 0);
@@ -891,7 +820,7 @@ const _ = new K(), j = class j extends Se {
891
820
  * Recommended: Use this instead of constructor for shared state
892
821
  */
893
822
  static getInstance(t = {}) {
894
- return _.get() || new j(t);
823
+ return $.get() || new D(t);
895
824
  }
896
825
  get isDev() {
897
826
  return this.settings.isDev ?? (typeof window < "u" ? window.location.hostname === "localhost" || window.location.hostname.includes("127.0.0.1") : !1);
@@ -920,18 +849,18 @@ const _ = new K(), j = class j extends Se {
920
849
  }
921
850
  // Full reset - clears session + state + destroys singleton
922
851
  clear() {
923
- this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = N({ prefix: "ses" }), _.delete();
852
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = O({ prefix: "ses" }), $.delete();
924
853
  }
925
854
  };
926
- d(j, "PageLinesSDK");
927
- let le = j;
855
+ c(D, "PageLinesSDK");
856
+ let Z = D;
928
857
  export {
929
- z as A,
930
- q as B,
931
- W as C,
932
- le as P,
933
- M as U,
934
- G as a,
935
- k as r
858
+ P as A,
859
+ L as B,
860
+ C,
861
+ Z as P,
862
+ j as U,
863
+ R as a,
864
+ p as r
936
865
  };
937
866
  //# sourceMappingURL=sdkClient.js.map