@pagelines/sdk 1.0.575 → 1.0.576

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,27 +1,27 @@
1
- var oe = Object.defineProperty;
2
- var ve = (n, e, t) => e in n ? oe(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
- var u = (n, e) => oe(n, "name", { value: e, configurable: !0 });
4
- var c = (n, e, t) => ve(n, typeof e != "symbol" ? e + "" : e, t);
5
- import { APP_PORT as pe, APP_PROD_URL as me, createRefreshingFetch as ye, cookieUtil as U, createLogger as we, shortId as xe, objectId as C, SettingsObject as Se } from "@pagelines/core";
6
- import { watch as N, ref as R, computed as ae } from "vue";
7
- function k(n, e) {
8
- return n || (e ? `http://localhost:${pe}` : me);
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);
9
9
  }
10
- u(k, "resolveApiBase");
11
- function ke(n, e, t) {
12
- const r = k(n.apiBase, n.isDev), s = t ? ye({
10
+ d(k, "resolveApiBase");
11
+ function be(a, e, t) {
12
+ const r = k(a.apiBase, a.isDev), o = t ? we({
13
13
  fetch: globalThis.fetch.bind(globalThis),
14
14
  getDeviceId: t.getDeviceId,
15
15
  refreshUrl: `${r}/api/auth/refresh`,
16
16
  onAccessTokenRefreshed: t.onAccessTokenRefreshed,
17
17
  onTerminalFailure: t.onTerminalFailure
18
18
  }) : globalThis.fetch.bind(globalThis);
19
- return async (o, i) => {
20
- const f = U.getAuthToken(), a = new Headers(i?.headers);
21
- a.has("Content-Type") || a.set("Content-Type", "application/json"), f && !a.has("Authorization") && a.set("Authorization", `Bearer ${f}`);
22
- const p = typeof o == "string" && o.startsWith("/") ? `${r}${o}` : o, g = await s(p, {
23
- ...i,
24
- headers: a,
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, {
23
+ ...n,
24
+ headers: i,
25
25
  credentials: "include"
26
26
  });
27
27
  if (e) {
@@ -34,31 +34,31 @@ function ke(n, e, t) {
34
34
  return g;
35
35
  };
36
36
  }
37
- u(ke, "createApiFetch");
38
- const Ie = /* @__PURE__ */ Symbol("clean");
37
+ d(be, "createApiFetch");
38
+ const Te = /* @__PURE__ */ Symbol("clean");
39
39
  let y = [], b = 0;
40
- const P = 4, be = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal = { epoch: 0 }), H = /* @__PURE__ */ u(/* @__NO_SIDE_EFFECTS__ */ (n) => {
40
+ const P = 4, Ee = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal = { epoch: 0 }), H = /* @__PURE__ */ d(/* @__NO_SIDE_EFFECTS__ */ (a) => {
41
41
  let e = [], t = {
42
42
  get() {
43
43
  return t.lc || t.listen(() => {
44
44
  })(), t.value;
45
45
  },
46
- init: n,
46
+ init: a,
47
47
  lc: 0,
48
48
  listen(r) {
49
49
  return t.lc = e.push(r), () => {
50
- for (let o = b + P; o < y.length; )
51
- y[o] === r ? y.splice(o, P) : o += P;
52
- let s = e.indexOf(r);
53
- ~s && (e.splice(s, 1), --t.lc || t.off());
50
+ for (let s = b + P; s < y.length; )
51
+ y[s] === r ? y.splice(s, P) : s += P;
52
+ let o = e.indexOf(r);
53
+ ~o && (e.splice(o, 1), --t.lc || t.off());
54
54
  };
55
55
  },
56
- notify(r, s) {
57
- be.epoch++;
58
- let o = !y.length;
59
- for (let i of e)
60
- y.push(i, t.value, r, s);
61
- if (o) {
56
+ notify(r, o) {
57
+ Ee.epoch++;
58
+ let s = !y.length;
59
+ for (let n of e)
60
+ y.push(n, t.value, r, o);
61
+ if (s) {
62
62
  for (b = 0; b < y.length; b += P)
63
63
  y[b](
64
64
  y[b + 1],
@@ -73,21 +73,21 @@ const P = 4, be = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
73
73
  off() {
74
74
  },
75
75
  set(r) {
76
- let s = t.value;
77
- s !== r && (t.value = r, t.notify(s));
76
+ let o = t.value;
77
+ o !== r && (t.value = r, t.notify(o));
78
78
  },
79
79
  subscribe(r) {
80
- let s = t.listen(r);
81
- return r(t.value), s;
80
+ let o = t.listen(r);
81
+ return r(t.value), o;
82
82
  },
83
- value: n
83
+ value: a
84
84
  };
85
- return process.env.NODE_ENV !== "production" && (t[Ie] = () => {
85
+ return process.env.NODE_ENV !== "production" && (t[Te] = () => {
86
86
  e = [], t.lc = 0, t.off();
87
87
  }), t;
88
- }, "atom"), I = globalThis, D = I.__PL_AUTH_USER__ ?? (I.__PL_AUTH_USER__ = /* @__PURE__ */ H(void 0)), B = I.__PL_AUTH_TOKEN__ ?? (I.__PL_AUTH_TOKEN__ = /* @__PURE__ */ H(null)), _ = I.__PL_AUTH_DEVICE_ID__ ?? (I.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ H(null)), V = class V {
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 {
89
89
  constructor() {
90
- c(this, "logger", we("SDKStorage"));
90
+ c(this, "logger", xe("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, be = 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: s } = e, o = D.get(), i = B.get(), f = _.get();
103
- o && (t.value = o), i && (r.value = i), f && (s.value = f), N(t, (a) => D.set(a), { immediate: !0 }), N(r, (a) => B.set(a), { immediate: !0 }), N(s, (a) => _.set(a), { immediate: !0 }), D.subscribe((a) => {
104
- a !== t.value && (t.value = a);
105
- }), B.subscribe((a) => {
106
- a !== r.value && (r.value = a);
107
- }), _.subscribe((a) => {
108
- a !== s.value && (s.value = a);
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);
109
109
  });
110
110
  }
111
111
  /**
@@ -120,10 +120,10 @@ const P = 4, be = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
120
120
  const r = U.getDeviceId();
121
121
  if (r && (e.deviceId.value = r), this.isLocalStorageFunctional())
122
122
  try {
123
- const s = localStorage.getItem("pagelines-user");
124
- s && (e.activeUser.value = JSON.parse(s));
125
- } catch (s) {
126
- this.logger.error("Failed to load user from localStorage", { data: s });
123
+ const o = localStorage.getItem("pagelines-user");
124
+ o && (e.activeUser.value = JSON.parse(o));
125
+ } catch (o) {
126
+ this.logger.error("Failed to load user from localStorage", { data: o });
127
127
  }
128
128
  }
129
129
  /**
@@ -151,7 +151,7 @@ const P = 4, be = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
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), _.set(null);
154
+ D.set(void 0), B.set(null), L.set(null);
155
155
  }
156
156
  }
157
157
  /**
@@ -178,15 +178,15 @@ const P = 4, be = globalThis.nanostoresGlobal || (globalThis.nanostoresGlobal =
178
178
  }
179
179
  }
180
180
  };
181
- u(V, "SDKStorage");
182
- let J = V;
183
- const Q = class Q {
181
+ d(Q, "SDKStorage");
182
+ let J = Q;
183
+ const V = class V {
184
184
  constructor(e) {
185
185
  c(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), o = await (await fetch(`${r}/api/agents`, {
189
+ const t = e.orgId || this.resolveOrgId(), r = k(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",
@@ -194,58 +194,70 @@ const Q = class Q {
194
194
  },
195
195
  body: JSON.stringify({ name: e.name, orgId: t })
196
196
  })).json();
197
- if (!o.ok || !o.data?.[0]) {
198
- const i = o.error || "Failed to create agent";
199
- throw this.ctx.error.value = i, new Error(i);
197
+ if (!s.ok || !s.data?.[0]) {
198
+ const n = s.error || "Failed to create agent";
199
+ throw this.ctx.error.value = n, new Error(n);
200
200
  }
201
- return this.ctx.processApiResponse(o), o.data[0];
201
+ return this.ctx.processApiResponse(s), s.data[0];
202
202
  }
203
- async getStatus(e) {
204
- const t = k(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${t}/api/agents/${e.agentId}/status`, {
205
- headers: {
206
- ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
207
- }
208
- })).json();
209
- return !s.ok || !s.data ? { status: "unknown", ready: !1, error: "Failed to check status" } : s.data;
203
+ /**
204
+ * Live runtime status the same canonical `LiveStatus` shape every other
205
+ * status producer emits (`GET /agents` rows, SSE status frames, lifecycle
206
+ * action responses). See plans/architecture/bot-state-management.md.
207
+ * `{ lifecycle: 'unknown' }` is the graceful degrade on any fetch failure.
208
+ */
209
+ async getLiveStatus(e) {
210
+ const t = k(this.ctx.apiBase, this.ctx.isDev);
211
+ try {
212
+ const o = await (await fetch(`${t}/api/agents/state?ids=${encodeURIComponent(e.agentId)}`, {
213
+ headers: {
214
+ ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
215
+ }
216
+ })).json();
217
+ return o.ok ? o.data?.[e.agentId] ?? { lifecycle: "unknown" } : { lifecycle: "unknown" };
218
+ } catch (r) {
219
+ return this.ctx.logger.warn("agent.getLiveStatus failed", {
220
+ agentId: e.agentId,
221
+ error: r instanceof Error ? r.message : String(r)
222
+ }), { lifecycle: "unknown" };
223
+ }
210
224
  }
211
225
  /**
212
- * Poll until the agent is ready. `onStatus` receives the server-reported
213
- * status string verbatim ('starting', 'running', …) so
214
- * the caller renders feedback tied to actual provisioner state, not a
215
- * rotating set of decorative messages decoupled from reality. Per
216
- * first-principles "Always give feedback no magic": a spinner that
217
- * emits unrelated copy is closer to magic than to feedback. Map status
218
- * names to user copy at the call site.
226
+ * Poll until the agent's lifecycle reaches `running`. `onStatus` receives
227
+ * the server-reported lifecycle verbatim ('starting', 'running', …) so the
228
+ * caller renders feedback tied to actual provisioner state, not a rotating
229
+ * set of decorative messages. Per first-principles "Always give feedback
230
+ * no magic". Map lifecycle values to user copy at the call site.
219
231
  */
220
232
  async waitUntilReady(e) {
221
- const { agentId: t, onStatus: r, timeoutMs: s = 3e5, pollIntervalMs: o = 3e3 } = e, i = Date.now();
233
+ const { agentId: t, onStatus: r, timeoutMs: o = 3e5, pollIntervalMs: s = 3e3 } = e, n = Date.now();
222
234
  let f;
223
- for (; Date.now() - i < s; ) {
224
- const a = await this.getStatus({ agentId: t });
225
- if (a.ready) {
235
+ for (; Date.now() - n < o; ) {
236
+ const i = await this.getLiveStatus({ agentId: t });
237
+ if (i.lifecycle === "running") {
226
238
  r?.("running");
227
239
  return;
228
240
  }
229
- if (a.status === "error")
230
- throw new Error(a.error || "Provisioning failed");
231
- a.status !== f && (r?.(a.status), f = a.status), await new Promise((p) => setTimeout(p, o));
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));
232
244
  }
233
- throw new Error("Agent provisioning timed out — please try again");
245
+ throw new Error("Your assistant is taking longer than expected — please try again");
234
246
  }
235
247
  /** Send a typed webhook event to a bot agent. No auth required — the proxy is public. */
236
248
  async webhook(e) {
237
- const r = `${k(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/webhooks/agents/${e.agentId}`, s = { type: e.type, data: e.data };
238
- e.meta && (s.meta = e.meta);
239
- const o = await fetch(r, {
249
+ const r = `${k(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/webhooks/agents/${e.agentId}`, o = { type: e.type, data: e.data };
250
+ e.meta && (o.meta = e.meta);
251
+ const s = await fetch(r, {
240
252
  method: "POST",
241
253
  headers: { "Content-Type": "application/json" },
242
- body: JSON.stringify(s)
254
+ body: JSON.stringify(o)
243
255
  });
244
- if (!o.ok) {
245
- const i = await o.text().catch(() => "Unknown error");
246
- throw new Error(`Webhook delivery failed (${o.status}): ${i.slice(0, 200)}`);
256
+ if (!s.ok) {
257
+ const n = await s.text().catch(() => "Unknown error");
258
+ throw new Error(`Webhook delivery failed (${s.status}): ${n.slice(0, 200)}`);
247
259
  }
248
- return o.json();
260
+ return s.json();
249
261
  }
250
262
  resolveOrgId() {
251
263
  const t = this.ctx.activeUser.value?.orgs?.[0]?.orgId;
@@ -254,18 +266,18 @@ const Q = class Q {
254
266
  return t;
255
267
  }
256
268
  };
257
- u(Q, "AgentClient");
258
- let G = Q;
259
- async function E(n, e) {
260
- n.loading.value = !0, n.error.value = null;
269
+ d(V, "AgentClient");
270
+ let z = V;
271
+ async function E(a, e) {
272
+ a.loading.value = !0, a.error.value = null;
261
273
  try {
262
274
  return await e();
263
275
  } finally {
264
- n.loading.value = !1;
276
+ a.loading.value = !1;
265
277
  }
266
278
  }
267
- u(E, "withLoadingState");
268
- const X = class X {
279
+ d(E, "withLoadingState");
280
+ const Y = class Y {
269
281
  constructor(e) {
270
282
  c(this, "ctx");
271
283
  this.ctx = e;
@@ -289,16 +301,16 @@ const X = class X {
289
301
  async verifyCode(e, t) {
290
302
  return E(this.ctx, async () => {
291
303
  try {
292
- const s = await (await this.ctx.apiFetch("/api/auth/verify-code", {
304
+ const o = await (await this.ctx.apiFetch("/api/auth/verify-code", {
293
305
  method: "POST",
294
306
  body: JSON.stringify({ email: e, code: t })
295
307
  })).json();
296
- if (!s.ok)
297
- throw this.ctx.error.value = s.error, new Error(s.error);
308
+ if (!o.ok)
309
+ throw this.ctx.error.value = o.error, new Error(o.error);
298
310
  } catch (r) {
299
311
  this.ctx.logger.error("Verify code error", { data: r });
300
- const s = r instanceof Error ? r.message : "Failed to verify code";
301
- throw this.ctx.error.value = s, r;
312
+ const o = r instanceof Error ? r.message : "Failed to verify code";
313
+ throw this.ctx.error.value = o, r;
302
314
  }
303
315
  });
304
316
  }
@@ -361,17 +373,17 @@ const X = class X {
361
373
  this.ctx.logger.error("loginWithGoogle: Only available in browser");
362
374
  return;
363
375
  }
364
- const t = k(this.ctx.apiBase, this.ctx.isDev), r = window.location.origin, s = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, o = 500, i = 600, f = window.screenX + (window.outerWidth - o) / 2, a = window.screenY + (window.outerHeight - i) / 2, p = window.open(
365
- s,
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(
377
+ o,
366
378
  "google-auth",
367
- `width=${o},height=${i},left=${f},top=${a},popup=yes`
379
+ `width=${s},height=${n},left=${f},top=${i},popup=yes`
368
380
  );
369
381
  if (!p) {
370
382
  const l = "Popup was blocked. Please allow popups for this site.";
371
383
  this.ctx.error.value = l, e?.onError?.(l);
372
384
  return;
373
385
  }
374
- const g = /* @__PURE__ */ u((l) => {
386
+ const g = /* @__PURE__ */ d((l) => {
375
387
  const m = new URL(t).origin;
376
388
  if (l.origin === m) {
377
389
  if (l.data?.type === "auth-success") {
@@ -391,15 +403,15 @@ const X = class X {
391
403
  }, 500);
392
404
  }
393
405
  };
394
- u(X, "AuthClient");
395
- let W = X;
396
- const Y = class Y {
406
+ d(Y, "AuthClient");
407
+ let G = Y;
408
+ const X = class X {
397
409
  constructor(e) {
398
410
  c(this, "ctx");
399
411
  this.ctx = e;
400
412
  }
401
413
  async startTrial(e) {
402
- const t = this.resolveOrgId(), r = k(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${r}/api/billing/checkout/create`, {
414
+ const t = this.resolveOrgId(), r = k(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${r}/api/billing/checkout/create`, {
403
415
  method: "POST",
404
416
  headers: {
405
417
  "Content-Type": "application/json",
@@ -411,36 +423,36 @@ const Y = class Y {
411
423
  ...e?.planKey && { planKey: e.planKey }
412
424
  })
413
425
  })).json();
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);
426
+ if (!s.ok || !s.data?.url) {
427
+ const n = s.error || "Failed to create checkout session";
428
+ throw this.ctx.error.value = n, new Error(n);
417
429
  }
418
- window.location.href = o.data.url;
430
+ window.location.href = s.data.url;
419
431
  }
420
432
  async confirmCheckout(e) {
421
433
  return this.getStatus();
422
434
  }
423
435
  async getStatus() {
424
- const e = this.resolveOrgId(), t = k(this.ctx.apiBase, this.ctx.isDev), s = await (await fetch(`${t}/api/billing/details/${e}`, {
436
+ const e = this.resolveOrgId(), t = k(this.ctx.apiBase, this.ctx.isDev), o = await (await fetch(`${t}/api/billing/details/${e}`, {
425
437
  headers: {
426
438
  ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
427
439
  }
428
440
  })).json();
429
- if (!s.ok || !s.data)
441
+ if (!o.ok || !o.data)
430
442
  return {
431
443
  plan: void 0,
432
444
  status: "none",
433
445
  hasActiveBilling: !1,
434
446
  maxAgents: 0
435
447
  };
436
- const o = ["active", "trialing"];
448
+ const s = ["active", "trialing"];
437
449
  return {
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 }
450
+ plan: o.data.plan,
451
+ status: o.data.status,
452
+ hasActiveBilling: s.includes(o.data.status),
453
+ maxAgents: o.data.maxAgents,
454
+ ...o.data.trialEnd && { trialEnd: o.data.trialEnd },
455
+ ...o.data.trialDaysRemaining !== void 0 && { trialDaysRemaining: o.data.trialDaysRemaining }
444
456
  };
445
457
  }
446
458
  resolveOrgId() {
@@ -450,39 +462,50 @@ const Y = class Y {
450
462
  return t;
451
463
  }
452
464
  };
453
- u(Y, "BillingClient");
454
- let q = Y;
455
- const Te = /* @__PURE__ */ new Set(["status", "message", "message_delta", "working_state", "working_end", "error", "stream_end"]);
456
- function ie(n) {
457
- const e = n.split(`
458
- `).filter((s) => s.length > 0);
465
+ d(X, "BillingClient");
466
+ let q = X;
467
+ function ie(a) {
468
+ const e = a.split(`
469
+ `).filter((o) => o.length > 0);
459
470
  let t, r;
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 || !Te.has(t))
471
+ for (const o of e)
472
+ o.startsWith("event:") ? t = o.slice(6).trim() : o.startsWith("data:") && (r = o.slice(5).trim());
473
+ if (!t || r === void 0)
463
474
  return null;
464
475
  try {
465
- return { event: t, data: JSON.parse(r) };
476
+ const o = ke.safeParse({ event: t, data: JSON.parse(r) });
477
+ return o.success ? o.data : null;
466
478
  } catch {
467
479
  return null;
468
480
  }
469
481
  }
470
- u(ie, "parseChatEvent");
471
- function ne(n) {
472
- if (!(n.role !== "assistant" && n.role !== "system"))
482
+ d(ie, "parseChatEvent");
483
+ function ne(a) {
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 } : {}
491
+ };
492
+ }
493
+ d(ne, "toChatStreamError");
494
+ function ce(a) {
495
+ if (!(a.role !== "assistant" && a.role !== "system"))
473
496
  return {
474
- id: n.messageId,
475
- text: n.content,
476
- sender: n.role === "system" ? "system" : "agent",
477
- timestamp: n.createdAt,
478
- conversationId: n.conversationId,
479
- sequence: n.sequence,
480
- systemKind: n.systemKind,
481
- ...n.metadata?.attachments?.length ? { attachments: n.metadata.attachments } : {},
482
- ...n.metadata?.issue ? { issue: n.metadata.issue } : {}
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 } : {}
483
506
  };
484
507
  }
485
- u(ne, "toChatMessage");
508
+ d(ce, "toChatMessage");
486
509
  const Z = class Z {
487
510
  constructor(e) {
488
511
  c(this, "ctx");
@@ -500,9 +523,9 @@ const Z = class Z {
500
523
  */
501
524
  async chatStreamPublic(e) {
502
525
  const r = `${k(this.ctx.apiBase, this.ctx.isDev)}/api/agents/public/${encodeURIComponent(e.handle)}/chat/v2/stream`;
503
- let s = "", o = !1, i = !1, f;
526
+ let o = "", s = !1, n = !1, f;
504
527
  try {
505
- const a = await fetch(r, {
528
+ const i = await fetch(r, {
506
529
  method: "POST",
507
530
  headers: { "Content-Type": "application/json" },
508
531
  body: JSON.stringify({
@@ -512,12 +535,12 @@ const Z = class Z {
512
535
  ...e.context ? { context: e.context } : {}
513
536
  })
514
537
  });
515
- if (!a.ok) {
516
- const w = await a.json().catch(() => ({ error: "Request failed" }));
517
- e.onError(w.error || `HTTP ${a.status}`);
538
+ if (!i.ok) {
539
+ const w = await i.json().catch(() => ({ error: "Request failed" }));
540
+ e.onError(w.error || `HTTP ${i.status}`);
518
541
  return;
519
542
  }
520
- if (s = a.headers.get("X-Conversation-Id") || "", f = a.body?.getReader(), !f) {
543
+ if (o = i.headers.get("X-Conversation-Id") || "", f = i.body?.getReader(), !f) {
521
544
  e.onError("No response stream");
522
545
  return;
523
546
  }
@@ -543,11 +566,11 @@ const Z = class Z {
543
566
  else if (h.event === "message_delta")
544
567
  e.onDelta(h.data.delta, h.data.role);
545
568
  else if (h.event === "error") {
546
- o = !0, e.onError(h.data.message);
569
+ s = !0, e.onError(ne(h.data));
547
570
  break e;
548
571
  } else if (h.event === "message" && (h.data.message.role === "assistant" || h.data.message.role === "system")) {
549
- i = !0;
550
- const A = ne(h.data.message);
572
+ n = !0;
573
+ const A = ce(h.data.message);
551
574
  A && e.onMessage?.(A);
552
575
  } else if (h.event === "stream_end")
553
576
  break e;
@@ -557,9 +580,9 @@ const Z = class Z {
557
580
  `);
558
581
  }
559
582
  }
560
- !o && i ? e.onDone(s) : o || e.onError("Stream ended before reply arrived");
561
- } catch (a) {
562
- e.onError(a instanceof Error ? a.message : "Stream failed");
583
+ !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");
563
586
  } finally {
564
587
  try {
565
588
  await f?.cancel();
@@ -577,82 +600,82 @@ const Z = class Z {
577
600
  */
578
601
  async chatStreamAuthenticated(e) {
579
602
  const t = k(this.ctx.apiBase, this.ctx.isDev), r = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {};
580
- let s, o = null;
603
+ let o, s = null;
581
604
  try {
582
- const d = await fetch(`${t}/api/conversations`, {
605
+ const u = await fetch(`${t}/api/conversations`, {
583
606
  method: "POST",
584
607
  headers: { "Content-Type": "application/json", ...r },
585
608
  body: JSON.stringify({ agentId: e.agentId })
586
- }), S = await d.json();
587
- if (!S.ok) {
588
- e.onError(S.error || `Conversation failed: HTTP ${d.status}`);
609
+ }), I = await u.json();
610
+ if (!I.ok) {
611
+ e.onError(I.error || `Conversation failed: HTTP ${u.status}`);
589
612
  return;
590
613
  }
591
- s = S.data.conversationId, o = S.data.latestSequence ?? null;
592
- } catch (d) {
593
- e.onError(d instanceof Error ? d.message : "Conversation failed");
614
+ o = I.data.conversationId, s = I.data.latestSequence ?? null;
615
+ } catch (u) {
616
+ e.onError(u instanceof Error ? u.message : "Conversation failed");
594
617
  return;
595
618
  }
596
- let i = !1, f = !1, a = !1, p = !1, g = !1, w = !1, l;
619
+ let n = !1, f = !1, i = !1, p = !1, g = !1, w = !1, l;
597
620
  const m = new AbortController();
598
- let x = !1, h, A = /* @__PURE__ */ u(() => {
621
+ let x = !1, h, A = /* @__PURE__ */ d(() => {
599
622
  }, "resolveStreamReady");
600
- const le = new Promise((d) => {
601
- A = d;
602
- }), $ = /* @__PURE__ */ u((d) => {
603
- x || (x = !0, h && clearTimeout(h), A(d));
604
- }, "settleStreamReady"), re = /* @__PURE__ */ u(() => {
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(() => {
605
628
  l?.cancel().catch(() => {
606
629
  });
607
- }, "cancelReader"), de = o ? `${t}/api/conversations/${encodeURIComponent(s)}/stream?since=${encodeURIComponent(o)}` : `${t}/api/conversations/${encodeURIComponent(s)}/stream`;
630
+ }, "cancelReader"), ue = s ? `${t}/api/conversations/${encodeURIComponent(o)}/stream?since=${encodeURIComponent(s)}` : `${t}/api/conversations/${encodeURIComponent(o)}/stream`;
608
631
  h = setTimeout(() => {
609
- w = !0, a = !0, e.onError("Timed out opening stream"), m.abort(), $("failed");
632
+ w = !0, i = !0, e.onError("Timed out opening stream"), m.abort(), $("failed");
610
633
  }, 1e4);
611
- const O = (async () => {
634
+ const R = (async () => {
612
635
  try {
613
- const d = await fetch(de, {
636
+ const u = await fetch(ue, {
614
637
  headers: r,
615
638
  signal: m.signal
616
639
  });
617
- if (!d.ok) {
618
- a = !0, $("failed"), e.onError(`Stream failed: HTTP ${d.status}`);
640
+ if (!u.ok) {
641
+ i = !0, $("failed"), e.onError(`Stream failed: HTTP ${u.status}`);
619
642
  return;
620
643
  }
621
- if (l = d.body?.getReader(), !l) {
622
- a = !0, $("failed"), e.onError("No response stream");
644
+ if (l = u.body?.getReader(), !l) {
645
+ i = !0, $("failed"), e.onError("No response stream");
623
646
  return;
624
647
  }
625
648
  $("ready");
626
- const S = new TextDecoder();
649
+ const I = new TextDecoder();
627
650
  let T = "";
628
651
  e: for (; ; ) {
629
- const { done: he, value: fe } = await l.read();
630
- if (he)
652
+ const { done: fe, value: ge } = await l.read();
653
+ if (fe)
631
654
  break;
632
- T += S.decode(fe, { stream: !0 });
655
+ T += I.decode(ge, { stream: !0 });
633
656
  let F = T.indexOf(`
634
657
 
635
658
  `);
636
659
  for (; F !== -1; ) {
637
- const ge = T.slice(0, F);
660
+ const ve = T.slice(0, F);
638
661
  T = T.slice(F + 2);
639
- const v = ie(ge);
662
+ const v = ie(ve);
640
663
  if (v) {
641
664
  if (v.event === "working_state")
642
- i && e.onStatus?.(v.data.description);
665
+ n && e.onStatus?.(v.data.description);
643
666
  else if (v.event === "working_end")
644
- i && e.onWorkingEnd?.();
667
+ n && e.onWorkingEnd?.();
645
668
  else if (v.event === "message_delta")
646
- i && e.onDelta(v.data.delta, v.data.role);
669
+ n && e.onDelta(v.data.delta, v.data.role);
647
670
  else if (v.event === "error") {
648
- a = !0, e.onError(v.data.message);
671
+ i = !0, e.onError(ne(v.data));
649
672
  break e;
650
673
  } else if (v.event === "message" && (v.data.message.role === "assistant" || v.data.message.role === "system")) {
651
- if (!i)
674
+ if (!n)
652
675
  continue;
653
676
  p = !0;
654
- const se = ne(v.data.message);
655
- se && e.onMessage?.(se);
677
+ const oe = ce(v.data.message);
678
+ oe && e.onMessage?.(oe);
656
679
  break e;
657
680
  } else if (v.event === "stream_end")
658
681
  break e;
@@ -662,9 +685,9 @@ const Z = class Z {
662
685
  `);
663
686
  }
664
687
  }
665
- !a && p ? e.onDone(s) : !a && i && !f && e.onError("Stream ended before reply arrived");
666
- } catch (d) {
667
- !f && !w && (a = !0, $("failed"), e.onError(d instanceof Error ? d.message : "Stream failed"));
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"));
668
691
  } finally {
669
692
  g = !0;
670
693
  try {
@@ -673,40 +696,40 @@ const Z = class Z {
673
696
  }
674
697
  }
675
698
  })();
676
- if (await le === "failed") {
677
- await O;
699
+ if (await de === "failed") {
700
+ await R;
678
701
  return;
679
702
  }
680
703
  if (g) {
681
- e.onError("Stream closed before send"), await O;
704
+ e.onError("Stream closed before send"), await R;
682
705
  return;
683
706
  }
684
- const ue = `nonce_${xe(16)}`;
707
+ const he = `nonce_${Ie(16)}`;
685
708
  try {
686
- i = !0;
687
- const d = await fetch(`${t}/api/messages`, {
709
+ n = !0;
710
+ const u = await fetch(`${t}/api/messages`, {
688
711
  method: "POST",
689
712
  headers: { "Content-Type": "application/json", ...r },
690
713
  body: JSON.stringify({
691
- conversationId: s,
714
+ conversationId: o,
692
715
  content: e.message,
693
- clientNonce: ue,
716
+ clientNonce: he,
694
717
  ...e.attachments && e.attachments.length > 0 ? { attachments: e.attachments } : {}
695
718
  })
696
- }), S = await d.json();
697
- if (!S.ok) {
698
- f = !0, m.abort(), re(), e.onError(S.error || `Send failed: HTTP ${d.status}`), await O;
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;
699
722
  return;
700
723
  }
701
- } catch (d) {
702
- f = !0, m.abort(), re(), e.onError(d instanceof Error ? d.message : "Send failed"), await O;
724
+ } catch (u) {
725
+ f = !0, m.abort(), re(), e.onError(u instanceof Error ? u.message : "Send failed"), await R;
703
726
  return;
704
727
  }
705
- await O;
728
+ await R;
706
729
  }
707
730
  };
708
- u(Z, "ChatClient");
709
- let z = Z;
731
+ d(Z, "ChatClient");
732
+ let W = Z;
710
733
  const ee = class ee {
711
734
  constructor(e) {
712
735
  c(this, "ctx");
@@ -747,7 +770,7 @@ const ee = class ee {
747
770
  generateAnonId() {
748
771
  const e = "pagelinesAnonId";
749
772
  let t = this.ctx.storage.getItem(e);
750
- return t || (t = C({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
773
+ return t || (t = N({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
751
774
  }
752
775
  track(e) {
753
776
  try {
@@ -762,7 +785,7 @@ const ee = class ee {
762
785
  }
763
786
  }
764
787
  };
765
- u(ee, "UserClient");
788
+ d(ee, "UserClient");
766
789
  let M = ee;
767
790
  const te = class te {
768
791
  constructor() {
@@ -779,28 +802,28 @@ const te = class te {
779
802
  typeof window < "u" && delete globalThis[this.key];
780
803
  }
781
804
  };
782
- u(te, "SDKGlobal");
805
+ d(te, "SDKGlobal");
783
806
  let K = te;
784
- const j = new K(), L = class L extends Se {
807
+ const _ = new K(), j = class j extends Se {
785
808
  constructor(t = {}) {
786
- const r = j.get();
809
+ const r = _.get();
787
810
  if (r)
788
811
  return console.debug("[PageLinesSDK] Returning existing singleton instance"), r;
789
812
  super("PageLinesSDK", t);
790
813
  // Vue reactive state
791
- c(this, "activeUser", R());
792
- c(this, "token", R(null));
814
+ c(this, "activeUser", O());
815
+ c(this, "token", O(null));
793
816
  // Refresh credential lives in HttpOnly pl-refresh-token cookie — JS never
794
817
  // holds it, so no reactive ref. /api/auth/refresh reads the cookie via the
795
818
  // browser's automatic credentials: 'include' attach.
796
- c(this, "deviceId", R(null));
797
- c(this, "loading", R(!1));
798
- c(this, "error", R(null));
819
+ c(this, "deviceId", O(null));
820
+ c(this, "loading", O(!1));
821
+ c(this, "error", O(null));
799
822
  c(this, "apiBase", this.settings.apiBase || void 0);
800
823
  // Storage handler for persistence
801
824
  c(this, "storage", new J());
802
825
  // Auto-managed session ID for usage tracking
803
- c(this, "sessionId", C({ prefix: "ses" }));
826
+ c(this, "sessionId", N({ prefix: "ses" }));
804
827
  // Computed properties derived from activeUser (matches UserClient pattern)
805
828
  c(this, "currentAgent", ae(() => {
806
829
  const t = this.activeUser.value;
@@ -808,7 +831,7 @@ const j = new K(), L = class L extends Se {
808
831
  return;
809
832
  const r = t.primaryAgentId || t.agents[0]?.agentId;
810
833
  if (r)
811
- return t.agents.find((s) => s.agentId === r);
834
+ return t.agents.find((o) => o.agentId === r);
812
835
  }));
813
836
  c(this, "currentOrg", ae(() => {
814
837
  const t = this.currentAgent.value;
@@ -816,7 +839,7 @@ const j = new K(), L = class L extends Se {
816
839
  return;
817
840
  const r = this.activeUser.value;
818
841
  if (r?.orgs)
819
- return r.orgs.find((s) => s.orgId === t.orgId);
842
+ return r.orgs.find((o) => o.orgId === t.orgId);
820
843
  }));
821
844
  // Initialization state
822
845
  c(this, "initialized");
@@ -827,17 +850,17 @@ const j = new K(), L = class L extends Se {
827
850
  c(this, "billing");
828
851
  c(this, "chat");
829
852
  c(this, "user");
830
- j.set(this);
831
- const o = {
832
- apiFetch: ke(
853
+ _.set(this);
854
+ const s = {
855
+ apiFetch: be(
833
856
  { isDev: this.isDev, apiBase: this.apiBase },
834
857
  this.processApiResponse.bind(this),
835
858
  {
836
- getDeviceId: /* @__PURE__ */ u(() => this.deviceId.value, "getDeviceId"),
837
- onAccessTokenRefreshed: /* @__PURE__ */ u((i) => {
838
- this.token.value = i, this.persistAuth();
859
+ getDeviceId: /* @__PURE__ */ d(() => this.deviceId.value, "getDeviceId"),
860
+ onAccessTokenRefreshed: /* @__PURE__ */ d((n) => {
861
+ this.token.value = n, this.persistAuth();
839
862
  }, "onAccessTokenRefreshed"),
840
- onTerminalFailure: /* @__PURE__ */ u(() => {
863
+ onTerminalFailure: /* @__PURE__ */ d(() => {
841
864
  this.clearSession();
842
865
  }, "onTerminalFailure")
843
866
  }
@@ -854,12 +877,12 @@ const j = new K(), L = class L extends Se {
854
877
  logger: this.logger,
855
878
  processApiResponse: this.processApiResponse.bind(this)
856
879
  };
857
- this.agent = new G(o), this.auth = new W(o), this.billing = new q(o), this.chat = new z(o), this.user = new M(o), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((i) => {
858
- this.resolveUser = i;
859
- }), this.token.value && !this.activeUser.value ? this.auth.getCurrentUser().then((i) => {
860
- this.resolveUser && (this.resolveUser(i), this.resolveUser = void 0);
861
- }).catch((i) => {
862
- this.logger.error("Auto user fetch failed", { data: i }), this.resolveUser && (this.resolveUser(void 0), this.resolveUser = void 0);
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) => {
881
+ this.resolveUser = n;
882
+ }), this.token.value && !this.activeUser.value ? this.auth.getCurrentUser().then((n) => {
883
+ this.resolveUser && (this.resolveUser(n), this.resolveUser = void 0);
884
+ }).catch((n) => {
885
+ this.logger.error("Auto user fetch failed", { data: n }), this.resolveUser && (this.resolveUser(void 0), this.resolveUser = void 0);
863
886
  }) : this.activeUser.value ? this.resolveUser?.(this.activeUser.value) : this.resolveUser?.(void 0);
864
887
  }
865
888
  /**
@@ -868,7 +891,7 @@ const j = new K(), L = class L extends Se {
868
891
  * Recommended: Use this instead of constructor for shared state
869
892
  */
870
893
  static getInstance(t = {}) {
871
- return j.get() || new L(t);
894
+ return _.get() || new j(t);
872
895
  }
873
896
  get isDev() {
874
897
  return this.settings.isDev ?? (typeof window < "u" ? window.location.hostname === "localhost" || window.location.hostname.includes("127.0.0.1") : !1);
@@ -878,8 +901,8 @@ const j = new K(), L = class L extends Se {
878
901
  if (!t.ok) return;
879
902
  let r = !1;
880
903
  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);
881
- const s = t.data?.deviceId;
882
- s && (this.deviceId.value = s, r = !0), r && this.persistAuth(), this.resolveUser && (this.resolveUser(t.user), this.resolveUser = void 0);
904
+ const o = t.data?.deviceId;
905
+ o && (this.deviceId.value = o, r = !0), r && this.persistAuth(), this.resolveUser && (this.resolveUser(t.user), this.resolveUser = void 0);
883
906
  }
884
907
  authRefs() {
885
908
  return {
@@ -897,18 +920,18 @@ const j = new K(), L = class L extends Se {
897
920
  }
898
921
  // Full reset - clears session + state + destroys singleton
899
922
  clear() {
900
- this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = C({ prefix: "ses" }), j.delete();
923
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = N({ prefix: "ses" }), _.delete();
901
924
  }
902
925
  };
903
- u(L, "PageLinesSDK");
904
- let ce = L;
926
+ d(j, "PageLinesSDK");
927
+ let le = j;
905
928
  export {
906
- G as A,
929
+ z as A,
907
930
  q as B,
908
- z as C,
909
- ce as P,
931
+ W as C,
932
+ le as P,
910
933
  M as U,
911
- W as a,
934
+ G as a,
912
935
  k as r
913
936
  };
914
937
  //# sourceMappingURL=sdkClient.js.map