@pagelines/sdk 1.0.878 → 1.0.880

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.
Files changed (92) hide show
  1. package/README.md +68 -68
  2. package/dist/BotProvider.js +777 -0
  3. package/dist/BotProvider.js.map +1 -0
  4. package/dist/{AgentWidgetInline.js → BotWidgetInline.js} +8 -8
  5. package/dist/BotWidgetInline.js.map +1 -0
  6. package/dist/{AgentWidgetModal.js → BotWidgetModal.js} +7 -7
  7. package/dist/BotWidgetModal.js.map +1 -0
  8. package/dist/{AgentWrap.js → BotWrap.js} +1174 -1145
  9. package/dist/BotWrap.js.map +1 -0
  10. package/dist/{agent/AgentController.d.ts → bot/BotController.d.ts} +35 -18
  11. package/dist/bot/index.d.ts +14 -0
  12. package/dist/{agent → bot}/schema.d.ts +6 -6
  13. package/dist/{agent/ui/AgentAvatar.vue.d.ts → bot/ui/BotAvatar.vue.d.ts} +6 -6
  14. package/dist/{agent/ui/AgentChat.vue.d.ts → bot/ui/BotChat.vue.d.ts} +5 -5
  15. package/dist/{agent/ui/AgentProvider.vue.d.ts → bot/ui/BotProvider.vue.d.ts} +3 -3
  16. package/dist/{agent/ui/AgentWrap.vue.d.ts → bot/ui/BotWrap.vue.d.ts} +3 -4
  17. package/dist/{agent/ui/ElAgentAbout.vue.d.ts → bot/ui/ElBotAbout.vue.d.ts} +2 -2
  18. package/dist/{agent/ui/ElAgentChat.vue.d.ts → bot/ui/ElBotChat.vue.d.ts} +5 -5
  19. package/dist/{agent/ui/ElAgentChatPreview.vue.d.ts → bot/ui/ElBotChatPreview.vue.d.ts} +1 -1
  20. package/dist/{agent/ui/ElAgentHeader.vue.d.ts → bot/ui/ElBotHeader.vue.d.ts} +2 -2
  21. package/dist/{agent/ui/ElAgentModeSidebar.vue.d.ts → bot/ui/ElBotModeSidebar.vue.d.ts} +2 -2
  22. package/dist/{agent/ui/ElAgentSidebar.vue.d.ts → bot/ui/ElBotSidebar.vue.d.ts} +2 -2
  23. package/dist/bot/ui/ElCreateBot.vue.d.ts +12 -0
  24. package/dist/{agent → bot}/ui/ElModeHeader.vue.d.ts +2 -2
  25. package/dist/{agent → bot}/ui/ElProvisioningStatus.vue.d.ts +1 -1
  26. package/dist/{agent → bot}/ui/VoiceMode.vue.d.ts +4 -4
  27. package/dist/{agent → bot}/utils.d.ts +5 -5
  28. package/dist/{agent → bot}/voice/provider.d.ts +2 -2
  29. package/dist/{agent → bot}/voice/providers/livekit/provider.d.ts +4 -4
  30. package/dist/{agent → bot}/voice/voice-session-client.d.ts +1 -1
  31. package/dist/{agent → bot}/work-journal.d.ts +1 -1
  32. package/dist/{agent.js → bot.js} +83 -80
  33. package/dist/bot.js.map +1 -0
  34. package/dist/clients/BillingClient.d.ts +1 -1
  35. package/dist/clients/BotClient.d.ts +26 -0
  36. package/dist/clients/ChatClient.d.ts +6 -5
  37. package/dist/clients/ComputerClient.d.ts +16 -0
  38. package/dist/clients/UserClient.d.ts +4 -7
  39. package/dist/clients/types.d.ts +7 -2
  40. package/dist/contract/build.d.ts +1 -2
  41. package/dist/index.d.ts +3 -2
  42. package/dist/provider.js +1 -1
  43. package/dist/provider.js.map +1 -1
  44. package/dist/provider2.js +14 -14
  45. package/dist/provider2.js.map +1 -1
  46. package/dist/sdk.css +1 -1
  47. package/dist/sdk.js +4 -4
  48. package/dist/sdkClient.d.ts +33 -376
  49. package/dist/sdkClient.js +168 -170
  50. package/dist/sdkClient.js.map +1 -1
  51. package/dist/useWidgetState.js +9 -9
  52. package/dist/useWidgetState.js.map +1 -1
  53. package/dist/widget/PLWidget.d.ts +6 -6
  54. package/dist/widget/composables/useWidgetState.d.ts +3 -402
  55. package/dist/widget/index.d.ts +2 -2
  56. package/dist/widget/mode.d.ts +2 -2
  57. package/dist/widget/ui/{AgentWidgetInline.vue.d.ts → BotWidgetInline.vue.d.ts} +2 -2
  58. package/dist/widget/ui/{AgentWidgetModal.vue.d.ts → BotWidgetModal.vue.d.ts} +2 -2
  59. package/dist/widget/ui/{AgentWidgetPopup.vue.d.ts → BotWidgetPopup.vue.d.ts} +4 -4
  60. package/dist/widget.js +206 -206
  61. package/dist/widget.js.map +1 -1
  62. package/package.json +5 -5
  63. package/dist/AgentProvider.js +0 -764
  64. package/dist/AgentProvider.js.map +0 -1
  65. package/dist/AgentWidgetInline.js.map +0 -1
  66. package/dist/AgentWidgetModal.js.map +0 -1
  67. package/dist/AgentWrap.js.map +0 -1
  68. package/dist/agent/index.d.ts +0 -14
  69. package/dist/agent/ui/ElCreateAgent.vue.d.ts +0 -277
  70. package/dist/agent.js.map +0 -1
  71. package/dist/clients/AgentClient.d.ts +0 -48
  72. /package/dist/{agent → bot}/VoiceRecorderController.d.ts +0 -0
  73. /package/dist/{agent/ui/AgentInputEmail.vue.d.ts → bot/ui/BotInputEmail.vue.d.ts} +0 -0
  74. /package/dist/{agent/ui/AgentInputOneTimeCode.vue.d.ts → bot/ui/BotInputOneTimeCode.vue.d.ts} +0 -0
  75. /package/dist/{agent/ui/AgentSidebarClose.vue.d.ts → bot/ui/BotSidebarClose.vue.d.ts} +0 -0
  76. /package/dist/{agent/ui/AgentToolActivityGroup.vue.d.ts → bot/ui/BotToolActivityGroup.vue.d.ts} +0 -0
  77. /package/dist/{agent/ui/AgentWidget.vue.d.ts → bot/ui/BotWidget.vue.d.ts} +0 -0
  78. /package/dist/{agent → bot}/ui/ChatCardBlock.vue.d.ts +0 -0
  79. /package/dist/{agent → bot}/ui/ChatRichText.vue.d.ts +0 -0
  80. /package/dist/{agent → bot}/ui/ChatScroller.vue.d.ts +0 -0
  81. /package/dist/{agent → bot}/ui/ChatVisualBlock.vue.d.ts +0 -0
  82. /package/dist/{agent → bot}/ui/ElAuthGate.vue.d.ts +0 -0
  83. /package/dist/{agent → bot}/ui/ElAuthPanel.vue.d.ts +0 -0
  84. /package/dist/{agent/ui/ElAgentButton.vue.d.ts → bot/ui/ElBotButton.vue.d.ts} +0 -0
  85. /package/dist/{agent → bot}/ui/ElSidebar.vue.d.ts +0 -0
  86. /package/dist/{agent → bot}/ui/VoiceHistogramController.d.ts +0 -0
  87. /package/dist/{agent → bot}/ui/chat-diagram-layout.d.ts +0 -0
  88. /package/dist/{agent → bot}/ui/chat-visual-format.d.ts +0 -0
  89. /package/dist/{agent → bot}/ui/voice-mode-presentation.d.ts +0 -0
  90. /package/dist/{agent → bot}/voice/voice-error-copy.d.ts +0 -0
  91. /package/dist/{agent → bot}/voice/voice-work-state.d.ts +0 -0
  92. /package/dist/widget/ui/{AgentWidgetOnboard.vue.d.ts → BotWidgetOnboard.vue.d.ts} +0 -0
package/dist/sdkClient.js CHANGED
@@ -1,22 +1,22 @@
1
1
  import "./rolldown-runtime.js";
2
- import { PAGELINES_APP_CONFIG as e, SettingsObject as t, cookieUtil as n, createLogger as r, objectId as i, readChatEventStream as a, runAuthenticatedChatTurnStream as o, serverTransitionBudgets as s, shortId as c, toChatStreamError as l } from "@pagelines/core";
3
- import { computed as u, ref as d, watch as f } from "vue";
2
+ import { Bot as e, Computer as t, PAGELINES_APP_CONFIG as n, SettingsObject as r, UNKNOWN_STATUS as i, cookieUtil as a, createLogger as o, detectBrowserTimezone as s, objectId as c, readChatEventStream as l, runAuthenticatedChatTurnStream as u, serverTransitionBudgets as d, shortId as f, toChatStreamError as p } from "@pagelines/core";
3
+ import { computed as m, ref as h, shallowReactive as g, watch as _ } from "vue";
4
4
  //#region api.ts
5
- function resolveApiBase(t, n) {
6
- let r = Number(globalThis.process?.env?.PORT) || e.port;
7
- return t || (n ? `http://localhost:${r}` : e.urls.app);
5
+ function resolveApiBase(e, t) {
6
+ let r = Number(globalThis.process?.env?.PORT) || n.port;
7
+ return e || (t ? `http://localhost:${r}` : n.urls.app);
8
8
  }
9
- function createApiFetch(e, t, r) {
10
- let i = resolveApiBase(e.apiBase, e.isDev);
11
- return async (e, a) => {
12
- let o = n.getAuthToken(), s = new Headers(a?.headers);
9
+ function createApiFetch(e, t, n) {
10
+ let r = resolveApiBase(e.apiBase, e.isDev);
11
+ return async (e, i) => {
12
+ let o = a.getAuthToken(), s = new Headers(i?.headers);
13
13
  s.has("Content-Type") || s.set("Content-Type", "application/json"), o && !s.has("Authorization") && s.set("Authorization", `Bearer ${o}`);
14
- let c = typeof e == "string" && e.startsWith("/") ? `${i}${e}` : e, l = await fetch(c, {
15
- ...a,
14
+ let c = typeof e == "string" && e.startsWith("/") ? `${r}${e}` : e, l = await fetch(c, {
15
+ ...i,
16
16
  headers: s,
17
17
  credentials: "include"
18
18
  });
19
- if (r && l.status === 401 && (await l.clone().json().catch(() => void 0))?.code === "TOKEN_ERROR" && r(), t) {
19
+ if (n && l.status === 401 && (await l.clone().json().catch(() => void 0))?.code === "TOKEN_ERROR" && n(), t) {
20
20
  let e = l.json.bind(l);
21
21
  l.json = async () => {
22
22
  let n = await e();
@@ -28,9 +28,9 @@ function createApiFetch(e, t, r) {
28
28
  }
29
29
  //#endregion
30
30
  //#region ../../node_modules/.pnpm/nanostores@1.4.1/node_modules/nanostores/clean-stores/index.js
31
- var p = Symbol("clean"), m, h = [], g = 0, _ = null, v = 4, y = (m = globalThis).nanostoresGlobal || (m.nanostoresGlobal = { epoch: 0 }), drainQueue = () => {
32
- for (g = 0; g < h.length; g += v) h[g](h[g + 1].value, h[g + 2], h[g + 3]);
33
- h.length = 0;
31
+ var v = Symbol("clean"), y, b = [], x = 0, S = null, C = 4, w = (y = globalThis).nanostoresGlobal || (y.nanostoresGlobal = { epoch: 0 }), drainQueue = () => {
32
+ for (x = 0; x < b.length; x += C) b[x](b[x + 1].value, b[x + 2], b[x + 3]);
33
+ b.length = 0;
34
34
  }, atom = /* @__NO_SIDE_EFFECTS__ */ (e) => {
35
35
  let t = [], n = {
36
36
  get() {
@@ -40,15 +40,15 @@ var p = Symbol("clean"), m, h = [], g = 0, _ = null, v = 4, y = (m = globalThis)
40
40
  lc: 0,
41
41
  listen(e) {
42
42
  return n.lc = t.push(e), () => {
43
- for (let t = g + v; t < h.length;) h[t] === e ? h.splice(t, v) : t += v;
43
+ for (let t = x + C; t < b.length;) b[t] === e ? b.splice(t, C) : t += C;
44
44
  let r = t.indexOf(e);
45
45
  ~r && (t.splice(r, 1), --n.lc || n.off());
46
46
  };
47
47
  },
48
48
  notify(e, r) {
49
- y.epoch++;
50
- let i = !h.length && !0;
51
- for (let i of t) _?.has(i) || (_?.add(i), h.push(i, n, e, r));
49
+ w.epoch++;
50
+ let i = !b.length && !0;
51
+ for (let i of t) S?.has(i) || (S?.add(i), b.push(i, n, e, r));
52
52
  i && drainQueue();
53
53
  },
54
54
  off() {},
@@ -62,7 +62,7 @@ var p = Symbol("clean"), m, h = [], g = 0, _ = null, v = 4, y = (m = globalThis)
62
62
  },
63
63
  value: e
64
64
  };
65
- return process.env.NODE_ENV !== "production" && (n[p] = () => {
65
+ return process.env.NODE_ENV !== "production" && (n[v] = () => {
66
66
  t = [], n.lc = 0, n.off();
67
67
  }), n;
68
68
  };
@@ -106,29 +106,29 @@ function _defineProperty(e, t, n) {
106
106
  }
107
107
  //#endregion
108
108
  //#region sdkStorage.ts
109
- var b = globalThis, x = b.__PL_AUTH_USER__ ?? (b.__PL_AUTH_USER__ = /* @__PURE__ */ atom(void 0)), S = b.__PL_AUTH_TOKEN__ ?? (b.__PL_AUTH_TOKEN__ = /* @__PURE__ */ atom(null)), C = b.__PL_AUTH_DEVICE_ID__ ?? (b.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ atom(null)), SDKStorage = class {
109
+ var T = globalThis, E = T.__PL_AUTH_USER__ ?? (T.__PL_AUTH_USER__ = /* @__PURE__ */ atom(void 0)), D = T.__PL_AUTH_TOKEN__ ?? (T.__PL_AUTH_TOKEN__ = /* @__PURE__ */ atom(null)), O = T.__PL_AUTH_DEVICE_ID__ ?? (T.__PL_AUTH_DEVICE_ID__ = /* @__PURE__ */ atom(null)), SDKStorage = class {
110
110
  constructor() {
111
- _defineProperty(this, "logger", r("SDKStorage"));
111
+ _defineProperty(this, "logger", o("SDKStorage"));
112
112
  }
113
113
  isLocalStorageFunctional() {
114
114
  return typeof window < "u" && typeof localStorage?.getItem == "function" && typeof localStorage?.setItem == "function" && typeof localStorage?.removeItem == "function";
115
115
  }
116
116
  syncWithGlobalStores(e) {
117
- let { activeUser: t, token: n, deviceId: r } = e, i = x.get(), a = S.get(), o = C.get();
118
- i && (t.value = i), a && (n.value = a), o && (r.value = o), f(t, (e) => x.set(e), { immediate: !0 }), f(n, (e) => S.set(e), { immediate: !0 }), f(r, (e) => C.set(e), { immediate: !0 }), x.subscribe((e) => {
117
+ let { activeUser: t, token: n, deviceId: r } = e, i = E.get(), a = D.get(), o = O.get();
118
+ i && (t.value = i), a && (n.value = a), o && (r.value = o), _(t, (e) => E.set(e), { immediate: !0 }), _(n, (e) => D.set(e), { immediate: !0 }), _(r, (e) => O.set(e), { immediate: !0 }), E.subscribe((e) => {
119
119
  e !== t.value && (t.value = e);
120
- }), S.subscribe((e) => {
120
+ }), D.subscribe((e) => {
121
121
  e !== n.value && (n.value = e);
122
- }), C.subscribe((e) => {
122
+ }), O.subscribe((e) => {
123
123
  e !== r.value && (r.value = e);
124
124
  });
125
125
  }
126
126
  loadFromStorage(e) {
127
127
  if (typeof window > "u") return;
128
- let t = n.getAuthToken();
128
+ let t = a.getAuthToken();
129
129
  t && (e.token.value = t);
130
- let r = n.getDeviceId();
131
- if (r && (e.deviceId.value = r), this.isLocalStorageFunctional()) try {
130
+ let n = a.getDeviceId();
131
+ if (n && (e.deviceId.value = n), this.isLocalStorageFunctional()) try {
132
132
  let t = localStorage.getItem("pagelines-user");
133
133
  t && (e.activeUser.value = JSON.parse(t));
134
134
  } catch (e) {
@@ -136,7 +136,7 @@ var b = globalThis, x = b.__PL_AUTH_USER__ ?? (b.__PL_AUTH_USER__ = /* @__PURE__
136
136
  }
137
137
  }
138
138
  saveToStorage(e) {
139
- if (!(typeof window > "u") && (e.token.value ? n.setAuthToken(e.token.value) : n.removeAuthToken(), this.isLocalStorageFunctional())) try {
139
+ if (!(typeof window > "u") && (e.token.value ? a.setAuthToken(e.token.value) : a.removeAuthToken(), this.isLocalStorageFunctional())) try {
140
140
  e.activeUser.value ? localStorage.setItem("pagelines-user", JSON.stringify(e.activeUser.value)) : localStorage.removeItem("pagelines-user");
141
141
  } catch (e) {
142
142
  this.logger.error("Failed to save user to localStorage", { data: e });
@@ -144,12 +144,12 @@ var b = globalThis, x = b.__PL_AUTH_USER__ ?? (b.__PL_AUTH_USER__ = /* @__PURE__
144
144
  }
145
145
  clearStorage() {
146
146
  if (!(typeof window > "u")) {
147
- if (n.removeAuthToken(), this.isLocalStorageFunctional()) try {
147
+ if (a.removeAuthToken(), this.isLocalStorageFunctional()) try {
148
148
  localStorage.removeItem("pagelines-user");
149
149
  } catch (e) {
150
150
  this.logger.error("Failed to clear user from localStorage", { data: e });
151
151
  }
152
- x.set(void 0), S.set(null), C.set(null);
152
+ E.set(void 0), D.set(null), O.set(null);
153
153
  }
154
154
  }
155
155
  getItem(e) {
@@ -173,77 +173,95 @@ var b = globalThis, x = b.__PL_AUTH_USER__ ?? (b.__PL_AUTH_USER__ = /* @__PURE__
173
173
  });
174
174
  }
175
175
  }
176
- }, AgentClient = class {
176
+ }, BotClient = class {
177
177
  constructor(e) {
178
- _defineProperty(this, "ctx", void 0), this.ctx = e;
178
+ _defineProperty(this, "ctx", void 0), _defineProperty(this, "computers", g(/* @__PURE__ */ new Map())), _defineProperty(this, "bots", g(/* @__PURE__ */ new Map())), this.ctx = e;
179
179
  }
180
- async create(e) {
181
- let t = e.orgId || this.resolveOrgId(), n = resolveApiBase(this.ctx.apiBase, this.ctx.isDev), r = await (await fetch(`${n}/api/agents`, {
180
+ get(e) {
181
+ return this.bots.get(e);
182
+ }
183
+ computer(e) {
184
+ return this.computers.get(e);
185
+ }
186
+ all() {
187
+ return [...this.bots.values()];
188
+ }
189
+ hydrate(n) {
190
+ for (let e of n.computers) {
191
+ let n = this.computers.get(e.computerId);
192
+ n ? n.merge(e) : this.computers.set(e.computerId, new t(e));
193
+ }
194
+ return n.bots.map((t) => {
195
+ let n = this.computers.get(t.computerId);
196
+ if (!n) throw Error("Bot references an unknown computer");
197
+ let r = this.bots.get(t.botId);
198
+ if (r) return r.merge(t), r;
199
+ let i = new e(t, n);
200
+ return this.bots.set(t.botId, i), i;
201
+ });
202
+ }
203
+ clear() {
204
+ this.bots.clear(), this.computers.clear();
205
+ }
206
+ async webhook(e) {
207
+ let t = await this.ctx.apiFetch(`/api/bot-api/webhooks/bots/${encodeURIComponent(e.botId)}`, {
182
208
  method: "POST",
183
209
  headers: {
184
210
  "Content-Type": "application/json",
185
- "Idempotency-Key": globalThis.crypto.randomUUID(),
186
- ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` }
211
+ "X-PageLines-Webhook-Key": e.key
187
212
  },
188
213
  body: JSON.stringify({
189
- name: e.name,
190
- orgId: t
214
+ type: e.type,
215
+ data: e.data,
216
+ ...e.meta ? { meta: e.meta } : {}
191
217
  })
218
+ });
219
+ if (!t.ok) throw Error(`Webhook delivery failed (${t.status})`);
220
+ return t.json();
221
+ }
222
+ }, ComputerClient = class {
223
+ constructor(e, t) {
224
+ _defineProperty(this, "ctx", void 0), _defineProperty(this, "registry", void 0), this.ctx = e, this.registry = t;
225
+ }
226
+ async create(e) {
227
+ let t = this.ctx.token.value, n = await (await this.ctx.apiFetch("/api/computers", {
228
+ method: "POST",
229
+ headers: {
230
+ "Content-Type": "application/json",
231
+ "Idempotency-Key": crypto.randomUUID()
232
+ },
233
+ body: JSON.stringify(e)
192
234
  })).json();
193
- if (!r.ok || !r.data) {
194
- let e = r.error || "Failed to create agent";
195
- throw this.ctx.error.value = e, Error(e);
196
- }
197
- return this.ctx.processApiResponse(r), r.data;
235
+ if (t !== this.ctx.token.value) throw Error("Your account changed. Try again.");
236
+ if (!n.ok) throw Error(n.error || "Failed to create computer");
237
+ return this.registry.hydrate({
238
+ computers: [n.data.computer],
239
+ bots: [n.data.bot]
240
+ })[0];
198
241
  }
199
242
  async getLiveStatus(e) {
200
- let t = resolveApiBase(this.ctx.apiBase, this.ctx.isDev);
243
+ let t = this.ctx.token.value;
201
244
  try {
202
- let n = await (await fetch(`${t}/api/agents/state?ids=${encodeURIComponent(e.agentId)}`, { headers: { ...this.ctx.token.value && { Authorization: `Bearer ${this.ctx.token.value}` } } })).json();
203
- return n.ok ? n.data?.[e.agentId] ?? { lifecycle: "unknown" } : { lifecycle: "unknown" };
245
+ let n = await (await this.ctx.apiFetch(`/api/computers/state?ids=${encodeURIComponent(e)}`)).json(), r = n.ok ? n.data[e] ?? i : i;
246
+ return t === this.ctx.token.value ? (this.registry.computer(e)?.merge(r), r) : i;
204
247
  } catch (t) {
205
- return this.ctx.logger.warn("agent.getLiveStatus failed", {
206
- agentId: e.agentId,
207
- error: t instanceof Error ? t.message : String(t)
208
- }), { lifecycle: "unknown" };
248
+ return this.ctx.logger.warn("Computer status unavailable", {
249
+ computerId: e,
250
+ error: t
251
+ }), i;
209
252
  }
210
253
  }
211
254
  async waitUntilReady(e) {
212
- let { agentId: t, onStatus: n, timeoutMs: r = s.wake, pollIntervalMs: i = 3e3 } = e, a = Date.now(), o;
213
- for (; Date.now() - a < r;) {
214
- let e = await this.getLiveStatus({ agentId: t });
215
- if (e.lifecycle === "running") {
216
- n?.("running");
217
- return;
218
- }
219
- if (e.lifecycle === "error") throw Error(e.detail || "Your bot hit a problem starting");
220
- e.lifecycle !== o && (n?.(e.lifecycle), o = e.lifecycle), await new Promise((e) => setTimeout(e, i));
221
- }
222
- throw Error("Your bot is taking longer than expected — please try again");
223
- }
224
- async webhook(e) {
225
- let t = `${resolveApiBase(this.ctx.apiBase, this.ctx.isDev)}/api/bot-api/webhooks/agents/${e.agentId}`, n = {
226
- type: e.type,
227
- data: e.data
228
- };
229
- e.meta && (n.meta = e.meta);
230
- let r = await fetch(t, {
231
- method: "POST",
232
- headers: { "Content-Type": "application/json" },
233
- body: JSON.stringify(n)
234
- });
235
- if (!r.ok) {
236
- let e = await r.text().catch(() => "Unknown error");
237
- throw Error(`Webhook delivery failed (${r.status}): ${e.slice(0, 200)}`);
255
+ let t = Date.now(), n;
256
+ for (; Date.now() - t < (e.timeoutMs ?? d.wake);) {
257
+ let t = await this.getLiveStatus(e.computerId);
258
+ if (t.lifecycle !== n && (e.onStatus?.(t.lifecycle), n = t.lifecycle), t.lifecycle === "running") return;
259
+ if (t.lifecycle === "error") throw Error("Your computer hit a problem starting");
260
+ await new Promise((t) => setTimeout(t, e.pollIntervalMs ?? 3e3));
238
261
  }
239
- return r.json();
262
+ throw Error("Your computer is taking longer than expected. Please try again.");
240
263
  }
241
- resolveOrgId() {
242
- let e = this.ctx.activeUser.value?.orgs?.[0]?.orgId;
243
- if (!e) throw Error("No organization found. Please sign in first.");
244
- return e;
245
- }
246
- }, w = "Signed in, but your account could not be loaded. Try again.";
264
+ }, k = "Signed in, but your account could not be loaded. Try again.";
247
265
  async function withLoadingState(e, t) {
248
266
  e.loading.value = !0, e.error.value = null;
249
267
  try {
@@ -266,7 +284,7 @@ var AuthClient = class {
266
284
  })).json();
267
285
  if (!n.ok) throw Error(n.error);
268
286
  let r = await this.getCurrentUser();
269
- if (!r) throw Error(w);
287
+ if (!r) throw Error(k);
270
288
  return r;
271
289
  }
272
290
  async sendCode(e) {
@@ -302,18 +320,20 @@ var AuthClient = class {
302
320
  } catch (e) {
303
321
  this.ctx.logger.error("Logout error (user still logged out locally)", { data: e });
304
322
  }
305
- this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage();
323
+ this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage(), this.ctx.clearRoster();
306
324
  });
307
325
  }
308
326
  async getCurrentUser() {
309
- if (this.ctx.token.value) return withLoadingState(this.ctx, async () => {
327
+ let e = this.ctx.token.value;
328
+ if (e) return withLoadingState(this.ctx, async () => {
310
329
  try {
311
- let e = await (await this.ctx.apiFetch("/api/users/me", { method: "GET" })).json();
312
- if (!e.ok) {
313
- this.ctx.error.value = e.error, e.error.includes("Authentication") && (this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage());
330
+ let t = await (await this.ctx.apiFetch("/api/users/me", { method: "GET" })).json();
331
+ if (e !== this.ctx.token.value) return;
332
+ if (!t.ok) {
333
+ this.ctx.error.value = t.error, t.error.includes("Authentication") && (this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage(), this.ctx.clearRoster());
314
334
  return;
315
335
  }
316
- return this.ctx.token.value && (this.ctx.activeUser.value = e.data), e.data;
336
+ return this.ctx.activeUser.value = t.data.user, this.ctx.hydrateRoster(t.data), t.data.user;
317
337
  } catch (e) {
318
338
  this.ctx.logger.error("Get current user error", { data: e }), this.ctx.error.value = e instanceof Error ? e.message : "Failed to get user info";
319
339
  return;
@@ -375,7 +395,7 @@ var AuthClient = class {
375
395
  });
376
396
  let r = await this.getCurrentUser();
377
397
  if (!r) {
378
- this.ctx.error.value = w, this.ctx.logger.error("Google login: token accepted but user hydration failed"), e?.onError?.(w);
398
+ this.ctx.error.value = k, this.ctx.logger.error("Google login: token accepted but user hydration failed"), e?.onError?.(k);
379
399
  return;
380
400
  }
381
401
  this.ctx.logger.info("Google login successful"), e?.onSuccess?.(r);
@@ -418,7 +438,7 @@ var AuthClient = class {
418
438
  plan: void 0,
419
439
  status: "none",
420
440
  hasActiveBilling: !1,
421
- maxAgents: 0
441
+ maxBots: 0
422
442
  };
423
443
  let r = [
424
444
  "active",
@@ -429,7 +449,7 @@ var AuthClient = class {
429
449
  plan: n.data.plan,
430
450
  status: n.data.status,
431
451
  hasActiveBilling: r,
432
- maxAgents: n.data.maxAgents,
452
+ maxBots: n.data.maxBots,
433
453
  ...n.data.trialEnd && { trialEnd: n.data.trialEnd },
434
454
  ...n.data.trialDaysRemaining !== void 0 && { trialDaysRemaining: n.data.trialDaysRemaining },
435
455
  ...n.data.paymentRecovery && { paymentRecovery: n.data.paymentRecovery }
@@ -446,18 +466,11 @@ var AuthClient = class {
446
466
  function toAuthenticatedTransportError(e) {
447
467
  return e.stage === "stream-open" && e.message.startsWith("HTTP ") ? `Stream failed: ${e.message}` : e.message;
448
468
  }
449
- function detectBrowserTimezone() {
450
- try {
451
- return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
452
- } catch {
453
- return;
454
- }
455
- }
456
469
  function toChatMessage(e) {
457
470
  if (!(e.role !== "assistant" && e.role !== "system")) return {
458
471
  id: e.messageId,
459
472
  text: e.content,
460
- sender: e.role === "system" ? "system" : "agent",
473
+ sender: e.role === "system" ? "system" : "bot",
461
474
  timestamp: e.createdAt,
462
475
  conversationId: e.conversationId,
463
476
  sequence: e.sequence,
@@ -485,9 +498,9 @@ var ChatClient = class {
485
498
  return i.data;
486
499
  }
487
500
  async chatStreamPublic(e) {
488
- let t = `${resolveApiBase(this.ctx.apiBase, this.ctx.isDev)}/api/agents/public/${encodeURIComponent(e.handle)}/chat/v2/stream`, n = "", r = !1, i = !1, o;
501
+ let t = `${resolveApiBase(this.ctx.apiBase, this.ctx.isDev)}/api/bots/public/${encodeURIComponent(e.handle)}/chat/stream`, n = "", r = !1, i = !1, a;
489
502
  try {
490
- let s = await fetch(t, {
503
+ let o = await fetch(t, {
491
504
  method: "POST",
492
505
  headers: { "Content-Type": "application/json" },
493
506
  body: JSON.stringify({
@@ -497,21 +510,21 @@ var ChatClient = class {
497
510
  ...e.context ? { context: e.context } : {}
498
511
  })
499
512
  });
500
- if (!s.ok) {
501
- let t = await s.json().catch(() => ({ error: "Request failed" }));
502
- e.onError(t.error || `HTTP ${s.status}`);
513
+ if (!o.ok) {
514
+ let t = await o.json().catch(() => ({ error: "Request failed" }));
515
+ e.onError(t.error || `HTTP ${o.status}`);
503
516
  return;
504
517
  }
505
- if (n = s.headers.get("X-Conversation-Id") || "", o = s.body?.getReader(), !o) {
518
+ if (n = o.headers.get("X-Conversation-Id") || "", a = o.body?.getReader(), !a) {
506
519
  e.onError("No response stream");
507
520
  return;
508
521
  }
509
- for await (let t of a(o)) if (t.event === "working_state") e.onStatus?.(t.data.description);
522
+ for await (let t of l(a)) if (t.event === "working_state") e.onStatus?.(t.data.description);
510
523
  else if (t.event === "tool_activity") e.onToolActivity?.(t.data);
511
524
  else if (t.event === "working_end") e.onWorkingEnd?.();
512
525
  else if (t.event === "message_delta") e.onDelta(t.data.delta, t.data.role);
513
526
  else if (t.event === "error") {
514
- r = !0, e.onError(l(t.data));
527
+ r = !0, e.onError(p(t.data));
515
528
  break;
516
529
  } else if (t.event === "message" && (t.data.message.role === "assistant" || t.data.message.role === "system")) {
517
530
  i = !0;
@@ -523,20 +536,26 @@ var ChatClient = class {
523
536
  e.onError(t instanceof Error ? t.message : "Stream failed");
524
537
  } finally {
525
538
  try {
526
- await o?.cancel();
539
+ await a?.cancel();
527
540
  } catch {}
528
541
  }
529
542
  }
530
543
  async chatStreamAuthenticated(e) {
531
- let t = resolveApiBase(this.ctx.apiBase, this.ctx.isDev), n = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {}, r, i = null;
532
- try {
544
+ let t = resolveApiBase(this.ctx.apiBase, this.ctx.isDev), n = this.ctx.token.value ? { Authorization: `Bearer ${this.ctx.token.value}` } : {}, r = e.conversationId, i = e.latestSequence ?? null;
545
+ if (!r) try {
533
546
  let a = await fetch(`${t}/api/conversations`, {
534
547
  method: "POST",
535
548
  headers: {
536
549
  "Content-Type": "application/json",
537
550
  ...n
538
551
  },
539
- body: JSON.stringify({ agentId: e.agentId })
552
+ body: JSON.stringify({
553
+ orgId: e.orgId,
554
+ participants: [{
555
+ type: "bot",
556
+ id: e.botId
557
+ }]
558
+ })
540
559
  }), o = await a.json();
541
560
  if (!o.ok) {
542
561
  e.onError(o.error || `Conversation failed: HTTP ${a.status}`);
@@ -547,16 +566,16 @@ var ChatClient = class {
547
566
  e.onError(t instanceof Error ? t.message : "Conversation failed");
548
567
  return;
549
568
  }
550
- let a = i ? `${t}/api/conversations/${encodeURIComponent(r)}/stream?since=${encodeURIComponent(i)}` : `${t}/api/conversations/${encodeURIComponent(r)}/stream`, s = `nonce_${c(16)}`, u = detectBrowserTimezone();
551
- await o({
569
+ let a = i ? `${t}/api/conversations/${encodeURIComponent(r)}/stream?since=${encodeURIComponent(i)}` : `${t}/api/conversations/${encodeURIComponent(r)}/stream`, o = `nonce_${f(16)}`, c = s();
570
+ await u({
552
571
  streamUrl: a,
553
572
  sendUrl: `${t}/api/messages`,
554
573
  headers: n,
555
574
  sendBody: {
556
575
  conversationId: r,
557
576
  content: e.message,
558
- clientNonce: s,
559
- ...u ? { viewerTimezone: u } : {},
577
+ clientNonce: o,
578
+ ...c ? { viewerTimezone: c } : {},
560
579
  ...e.attachments && e.attachments.length > 0 ? { attachments: e.attachments } : {}
561
580
  },
562
581
  onStatus: e.onStatus,
@@ -568,7 +587,7 @@ var ChatClient = class {
568
587
  n && e.onMessage?.(n);
569
588
  },
570
589
  onDone: () => e.onDone(r),
571
- onChatError: (t) => e.onError(l(t)),
590
+ onChatError: (t) => e.onError(p(t)),
572
591
  onTransportError: (t) => e.onError(t.code ? {
573
592
  code: t.code,
574
593
  error: t.message
@@ -579,45 +598,26 @@ var ChatClient = class {
579
598
  constructor(e) {
580
599
  _defineProperty(this, "ctx", void 0), this.ctx = e;
581
600
  }
582
- async getPublicAgent(e) {
601
+ async getPublicBot(e) {
583
602
  this.ctx.loading.value = !0, this.ctx.error.value = null;
584
603
  try {
585
- let t = await (await this.ctx.apiFetch(`/api/agents/public/${encodeURIComponent(e.handle)}`)).json();
604
+ let t = await (await this.ctx.apiFetch(`/api/pub/bot/get-by-handle?handle=${encodeURIComponent(e.handle)}`)).json();
586
605
  if (!t.ok) {
587
- this.ctx.error.value = t.error, this.ctx.logger.error("Failed to fetch public agent", {
606
+ this.ctx.error.value = t.error, this.ctx.logger.error("Failed to fetch public bot", {
588
607
  handle: e.handle,
589
608
  error: t.error
590
609
  });
591
610
  return;
592
611
  }
593
- return t.data;
612
+ return this.ctx.hydrateRoster({
613
+ bots: [t.data.bot],
614
+ computers: [t.data.computer]
615
+ })[0];
594
616
  } catch (t) {
595
- this.ctx.logger.error("Get public agent error", {
617
+ this.ctx.logger.error("Get public bot error", {
596
618
  handle: e.handle,
597
619
  error: t
598
- }), this.ctx.error.value = t instanceof Error ? t.message : "Failed to fetch agent";
599
- return;
600
- } finally {
601
- this.ctx.loading.value = !1;
602
- }
603
- }
604
- async getAgentByEmail(e) {
605
- this.ctx.loading.value = !0, this.ctx.error.value = null;
606
- try {
607
- let t = await (await this.ctx.apiFetch(`/api/agents/by-email/${encodeURIComponent(e.email)}`)).json();
608
- if (!t.ok) {
609
- this.ctx.error.value = t.error, this.ctx.logger.error("Failed to fetch agent by email", {
610
- email: e.email,
611
- error: t.error
612
- });
613
- return;
614
- }
615
- return t.data;
616
- } catch (t) {
617
- this.ctx.logger.error("Get agent by email error", {
618
- email: e.email,
619
- error: t
620
- }), this.ctx.error.value = t instanceof Error ? t.message : "Failed to fetch agent";
620
+ }), this.ctx.error.value = t instanceof Error ? t.message : "Failed to fetch bot";
621
621
  return;
622
622
  } finally {
623
623
  this.ctx.loading.value = !1;
@@ -625,18 +625,18 @@ var ChatClient = class {
625
625
  }
626
626
  generateAnonId() {
627
627
  let e = "pagelinesAnonId", t = this.ctx.storage.getItem(e);
628
- return t || (t = i({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
628
+ return t || (t = c({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
629
629
  }
630
630
  track(e) {
631
631
  try {
632
632
  typeof window < "u" && window.parent !== window && window.parent.postMessage({
633
633
  type: "pagelines_track",
634
634
  event: e.event,
635
- agentId: e.agentId,
635
+ botId: e.botId,
636
636
  properties: e.properties || {}
637
637
  }, "*"), this.ctx.logger.info("SDK event tracked", {
638
638
  event: e.event,
639
- agentId: e.agentId
639
+ botId: e.botId
640
640
  });
641
641
  } catch (t) {
642
642
  this.ctx.logger.error("Track event error", {
@@ -658,27 +658,23 @@ var ChatClient = class {
658
658
  delete() {
659
659
  typeof window < "u" && delete globalThis[this.key];
660
660
  }
661
- }, T = new SDKGlobal(), E = class PageLinesSDK extends t {
661
+ }, A = new SDKGlobal(), j = class PageLinesSDK extends r {
662
662
  static getInstance(e = {}) {
663
- return T.get() || new PageLinesSDK(e);
663
+ return A.get() || new PageLinesSDK(e);
664
664
  }
665
665
  get isDev() {
666
666
  return this.settings.isDev ?? (typeof window < "u" ? window.location.hostname === "localhost" || window.location.hostname.includes("127.0.0.1") : !1);
667
667
  }
668
668
  constructor(e = {}) {
669
- let t = T.get();
669
+ let t = A.get();
670
670
  if (t) return console.debug("[PageLinesSDK] Returning existing singleton instance"), t;
671
- super("PageLinesSDK", e), _defineProperty(this, "activeUser", d()), _defineProperty(this, "token", d(null)), _defineProperty(this, "deviceId", d(null)), _defineProperty(this, "loading", d(!1)), _defineProperty(this, "error", d(null)), _defineProperty(this, "apiBase", this.settings.apiBase || void 0), _defineProperty(this, "storage", new SDKStorage()), _defineProperty(this, "sessionId", i({ prefix: "ses" })), _defineProperty(this, "currentAgent", u(() => {
671
+ super("PageLinesSDK", e), _defineProperty(this, "activeUser", h()), _defineProperty(this, "token", h(null)), _defineProperty(this, "deviceId", h(null)), _defineProperty(this, "loading", h(!1)), _defineProperty(this, "error", h(null)), _defineProperty(this, "apiBase", this.settings.apiBase || void 0), _defineProperty(this, "storage", new SDKStorage()), _defineProperty(this, "sessionId", c({ prefix: "ses" })), _defineProperty(this, "currentBot", m(() => {
672
672
  let e = this.activeUser.value;
673
- if (!e?.agents) return;
674
- let t = e.primaryAgentId || e.agents[0]?.agentId;
675
- if (t) return e.agents.find((e) => e.agentId === t);
676
- })), _defineProperty(this, "currentOrg", u(() => {
677
- let e = this.currentAgent.value;
678
- if (!e?.orgId) return;
679
- let t = this.activeUser.value;
680
- if (t?.orgs) return t.orgs.find((t) => t.orgId === e.orgId);
681
- })), _defineProperty(this, "initialized", void 0), _defineProperty(this, "resolveUser", void 0), _defineProperty(this, "agent", void 0), _defineProperty(this, "auth", void 0), _defineProperty(this, "billing", void 0), _defineProperty(this, "chat", void 0), _defineProperty(this, "user", void 0), T.set(this);
673
+ return (e?.lastBotId ? this.bot.get(e.lastBotId) : void 0) ?? this.bot.all().find((t) => t.isPrimary.value && t.ownerId.value === e?.userId);
674
+ })), _defineProperty(this, "currentOrg", m(() => {
675
+ let e = this.currentBot.value?.computer.orgId.value ?? this.activeUser.value?.lastActiveOrgId ?? this.activeUser.value?.primaryOrgId;
676
+ return this.activeUser.value?.orgs?.find((t) => t.orgId === e);
677
+ })), _defineProperty(this, "initialized", void 0), _defineProperty(this, "resolveUser", void 0), _defineProperty(this, "bot", void 0), _defineProperty(this, "computer", void 0), _defineProperty(this, "auth", void 0), _defineProperty(this, "billing", void 0), _defineProperty(this, "chat", void 0), _defineProperty(this, "user", void 0), _defineProperty(this, "stopAccountWatch", void 0), A.set(this);
682
678
  let n = {
683
679
  apiFetch: createApiFetch({
684
680
  isDev: this.isDev,
@@ -690,13 +686,15 @@ var ChatClient = class {
690
686
  token: this.token,
691
687
  loading: this.loading,
692
688
  error: this.error,
693
- currentAgent: this.currentAgent,
689
+ currentBot: this.currentBot,
690
+ hydrateRoster: (e) => this.bot.hydrate(e),
691
+ clearRoster: () => this.bot.clear(),
694
692
  storage: this.storage,
695
693
  sessionId: this.sessionId,
696
694
  logger: this.logger,
697
695
  processApiResponse: this.processApiResponse.bind(this)
698
696
  };
699
- this.agent = new AgentClient(n), this.auth = new AuthClient(n), this.billing = new BillingClient(n), this.chat = new ChatClient(n), this.user = new UserClient(n), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((e) => {
697
+ this.bot = new BotClient(n), this.computer = new ComputerClient(n, this.bot), this.auth = new AuthClient(n), this.billing = new BillingClient(n), this.chat = new ChatClient(n), this.user = new UserClient(n), this.stopAccountWatch = _(() => this.activeUser.value?.userId, () => this.bot.clear(), { flush: "sync" }), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.authRefs()), this.storage.syncWithGlobalStores(this.authRefs()), this.initialized = new Promise((e) => {
700
698
  this.resolveUser = e;
701
699
  }), this.token.value && !this.activeUser.value ? this.auth.getCurrentUser().then((e) => {
702
700
  this.resolveUser && (this.resolveUser(e), this.resolveUser = void 0);
@@ -707,7 +705,7 @@ var ChatClient = class {
707
705
  processApiResponse(e) {
708
706
  if (!e.ok) return;
709
707
  let t = !1;
710
- e.user && (this.activeUser.value = e.user, this.logger.info("User updated from API response", { data: e.user }), t = !0), e.token && (this.token.value = e.token, this.logger.info("Token updated from API response"), t = !0);
708
+ e.user && (this.activeUser.value = e.user, this.logger.info("User updated from API response", { data: e.user }), t = !0), e.token && (this.token.value !== e.token && (this.activeUser.value = void 0, this.bot.clear()), this.token.value = e.token, this.logger.info("Token updated from API response"), t = !0);
711
709
  let n = e.data?.deviceId;
712
710
  n && (this.deviceId.value = n, t = !0), t && this.persistAuth(), this.resolveUser && (this.resolveUser(e.user), this.resolveUser = void 0);
713
711
  }
@@ -722,13 +720,13 @@ var ChatClient = class {
722
720
  this.storage.saveToStorage(this.authRefs());
723
721
  }
724
722
  clearSession() {
725
- this.logger.info("Clearing session"), this.activeUser.value = void 0, this.token.value = null, this.deviceId.value = null, this.error.value = null, this.storage.clearStorage();
723
+ this.bot.clear(), this.logger.info("Clearing session"), this.activeUser.value = void 0, this.token.value = null, this.deviceId.value = null, this.error.value = null, this.storage.clearStorage();
726
724
  }
727
725
  clear() {
728
- this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = i({ prefix: "ses" }), T.delete();
726
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = c({ prefix: "ses" }), this.stopAccountWatch?.(), A.delete();
729
727
  }
730
728
  };
731
729
  //#endregion
732
- export { AuthClient as a, resolveApiBase as c, BillingClient as i, UserClient as n, AgentClient as o, ChatClient as r, _defineProperty as s, E as t };
730
+ export { AuthClient as a, _defineProperty as c, BillingClient as i, resolveApiBase as l, UserClient as n, ComputerClient as o, ChatClient as r, BotClient as s, j as t };
733
731
 
734
732
  //# sourceMappingURL=sdkClient.js.map