@gentiq/core 1.0.0-alpha.12 → 1.0.0-alpha.14

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.
@@ -1,51 +1,54 @@
1
- function p(r) {
2
- return r ?? "";
1
+ function p(t) {
2
+ return t ?? "";
3
3
  }
4
4
  const u = { text: "", references: [], voiceInputs: [] };
5
- function d(r) {
5
+ function a(t) {
6
6
  return [
7
- r.sourceId,
8
- r.messageId,
9
- r.partIndex,
10
- r.kind,
11
- r.excerpt.replace(/\s+/g, " ").trim()
12
- ].filter((s) => s !== void 0 && s !== "").join(":");
7
+ t.sourceId,
8
+ t.messageId,
9
+ t.partIndex,
10
+ t.kind,
11
+ t.excerpt.replace(/\s+/g, " ").trim()
12
+ ].filter((c) => c !== void 0 && c !== "").join(":");
13
13
  }
14
14
  function g() {
15
- const r = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set(), o = (e) => r.get(e) ?? u;
16
- function f(e, t) {
17
- const n = o(e), c = { ...n, ...t(n) };
18
- c.text === "" && c.references.length === 0 && c.voiceInputs.length === 0 ? r.delete(e) : r.set(e, c), s.forEach((i) => i());
15
+ const t = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Set(), o = (e) => t.get(e) ?? u;
16
+ function f(e, r) {
17
+ const n = o(e), s = { ...n, ...r(n) };
18
+ s.text === "" && s.references.length === 0 && s.voiceInputs.length === 0 ? t.delete(e) : t.set(e, s), c.forEach((i) => i());
19
19
  }
20
20
  return {
21
21
  get: o,
22
22
  subscribe(e) {
23
- return s.add(e), () => {
24
- s.delete(e);
23
+ return c.add(e), () => {
24
+ c.delete(e);
25
25
  };
26
26
  },
27
- setText: (e, t) => {
28
- o(e).text !== t && f(e, () => ({ text: t }));
27
+ setText: (e, r) => {
28
+ o(e).text !== r && f(e, () => ({ text: r }));
29
29
  },
30
- addReference: (e, t, n) => f(e, ({ references: c }) => {
31
- const i = d(t), a = c.filter((l) => d(l) !== i);
32
- return { references: [t, ...a].slice(0, n) };
30
+ addReference: (e, r, n) => f(e, ({ references: s }) => {
31
+ const i = a(r), d = s.filter((l) => a(l) !== i);
32
+ return { references: [r, ...d].slice(0, n) };
33
33
  }),
34
- removeReference: (e, t) => f(e, ({ references: n }) => ({
35
- references: n.filter((c) => c.id !== t)
34
+ removeReference: (e, r) => f(e, ({ references: n }) => ({
35
+ references: n.filter((s) => s.id !== r)
36
36
  })),
37
37
  clearReferences: (e) => {
38
38
  o(e).references.length > 0 && f(e, () => ({ references: [] }));
39
39
  },
40
- addVoiceInput: (e, t) => f(e, ({ voiceInputs: n }) => ({ voiceInputs: [...n, t] })),
40
+ addVoiceInput: (e, r) => f(e, ({ voiceInputs: n }) => ({ voiceInputs: [...n, r] })),
41
41
  take: (e) => {
42
- const t = o(e);
43
- return t !== u && (r.delete(e), s.forEach((n) => n())), t;
42
+ const r = o(e);
43
+ return r !== u && (t.delete(e), c.forEach((n) => n())), r;
44
+ },
45
+ clear() {
46
+ t.size !== 0 && (t.clear(), c.forEach((e) => e()));
44
47
  }
45
48
  };
46
49
  }
47
50
  export {
48
51
  p as composerScope,
49
52
  g as createComposerDrafts,
50
- d as referenceSourceKey
53
+ a as referenceSourceKey
51
54
  };
@@ -1,44 +1,44 @@
1
1
  import { isClientError as y } from "../errors.es.js";
2
- const a = [];
3
- function m(c) {
4
- const s = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Set();
2
+ const i = [];
3
+ function m(g) {
4
+ const n = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Set();
5
5
  let k = 0;
6
- const i = () => d.forEach((e) => e());
7
- function f(e, t, n) {
8
- const r = s.get(e);
9
- r?.some((l) => l.key === t) && (s.set(
6
+ const a = () => u.forEach((e) => e());
7
+ function f(e, t, s) {
8
+ const r = n.get(e);
9
+ r?.some((l) => l.key === t) && (n.set(
10
10
  e,
11
- r.map((l) => l.key === t ? { ...l, ...n } : l)
12
- ), i());
11
+ r.map((l) => l.key === t ? { ...l, ...s } : l)
12
+ ), a());
13
13
  }
14
- function u(e, t) {
15
- const n = new AbortController();
16
- o.set(t.key, n), c(t.file, {
17
- signal: n.signal,
14
+ function c(e, t) {
15
+ const s = new AbortController();
16
+ o.set(t.key, s), g(t.file, {
17
+ signal: s.signal,
18
18
  onProgress: (r) => f(e, t.key, { progress: r })
19
19
  }).then(
20
20
  (r) => {
21
21
  o.delete(t.key), f(e, t.key, { status: "uploaded", progress: 1, attachment: r });
22
22
  },
23
23
  (r) => {
24
- o.delete(t.key), !n.signal.aborted && f(e, t.key, { status: "failed", error: r, retryable: !y(r) });
24
+ o.delete(t.key), !s.signal.aborted && f(e, t.key, { status: "failed", error: r, retryable: !y(r) });
25
25
  }
26
26
  );
27
27
  }
28
- function g(e) {
28
+ function d(e) {
29
29
  for (const t of e)
30
30
  o.get(t.key)?.abort(), o.delete(t.key);
31
31
  }
32
32
  return {
33
- get: (e) => s.get(e) ?? a,
33
+ get: (e) => n.get(e) ?? i,
34
34
  subscribe(e) {
35
- return d.add(e), () => {
36
- d.delete(e);
35
+ return u.add(e), () => {
36
+ u.delete(e);
37
37
  };
38
38
  },
39
39
  add(e, t) {
40
40
  if (t.length === 0) return;
41
- const n = t.map(
41
+ const s = t.map(
42
42
  (r) => ({
43
43
  key: `file-${k++}`,
44
44
  file: r,
@@ -47,30 +47,34 @@ function m(c) {
47
47
  retryable: !1
48
48
  })
49
49
  );
50
- s.set(e, [...s.get(e) ?? a, ...n]), i(), n.forEach((r) => u(e, r));
50
+ n.set(e, [...n.get(e) ?? i, ...s]), a(), s.forEach((r) => c(e, r));
51
51
  },
52
52
  remove(e, t) {
53
- const n = s.get(e) ?? a;
54
- g(n.filter((r) => r.key === t)), s.set(
53
+ const s = n.get(e) ?? i;
54
+ d(s.filter((r) => r.key === t)), n.set(
55
55
  e,
56
- n.filter((r) => r.key !== t)
57
- ), i();
56
+ s.filter((r) => r.key !== t)
57
+ ), a();
58
58
  },
59
59
  retry(e, t) {
60
- const n = s.get(e)?.find((l) => l.key === t);
61
- if (!n || n.status !== "failed") return;
60
+ const s = n.get(e)?.find((l) => l.key === t);
61
+ if (!s || s.status !== "failed") return;
62
62
  const r = {
63
- key: n.key,
64
- file: n.file,
63
+ key: s.key,
64
+ file: s.file,
65
65
  status: "uploading",
66
66
  progress: null,
67
67
  retryable: !1
68
68
  };
69
- f(e, t, { ...r, error: void 0, attachment: void 0 }), u(e, r);
69
+ f(e, t, { ...r, error: void 0, attachment: void 0 }), c(e, r);
70
70
  },
71
71
  take(e) {
72
- const t = s.get(e) ?? a;
73
- return t.length === 0 ? a : (g(t), s.delete(e), i(), t);
72
+ const t = n.get(e) ?? i;
73
+ return t.length === 0 ? i : (d(t), n.delete(e), a(), t);
74
+ },
75
+ clear() {
76
+ for (const e of n.values()) d(e);
77
+ n.size === 0 && o.size === 0 || (n.clear(), a());
74
78
  }
75
79
  };
76
80
  }
package/dist/index.d.ts CHANGED
@@ -357,6 +357,8 @@ declare function buildApi(http: HttpClient, auth: ResolvedAuthAdapter, options:
357
357
  week_start?: ("monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday") | null;
358
358
  welcome_greeting?: string | null;
359
359
  welcome_subtitle?: string | null;
360
+ } & {
361
+ [key: string]: unknown;
360
362
  }>;
361
363
  /** Whether the service is under maintenance. Public; polled by `useGentiqStatus`. */
362
364
  getStatus: (signal?: AbortSignal) => Promise<{
@@ -1551,7 +1553,7 @@ declare interface components {
1551
1553
  /** Surname */
1552
1554
  surname: string | null;
1553
1555
  /** Token */
1554
- token: string;
1556
+ token?: string | null;
1555
1557
  /** Username */
1556
1558
  username: string | null;
1557
1559
  };
@@ -1593,7 +1595,7 @@ declare interface components {
1593
1595
  /** Surname */
1594
1596
  surname: string | null;
1595
1597
  /** Token */
1596
- token: string;
1598
+ token?: string | null;
1597
1599
  /**
1598
1600
  * Type
1599
1601
  * @enum {string}
@@ -1607,6 +1609,8 @@ declare interface components {
1607
1609
  * @description An admin's edit of a user. Unlike a user's edit of themselves, it can set the user's group.
1608
1610
  */
1609
1611
  AdminUserUpdateInput: {
1612
+ /** Current Password */
1613
+ current_password?: string | null;
1610
1614
  /** Email */
1611
1615
  email?: string | null;
1612
1616
  /** Metadata */
@@ -3705,6 +3709,8 @@ declare interface components {
3705
3709
  welcome_greeting?: string | null;
3706
3710
  /** Welcome Subtitle */
3707
3711
  welcome_subtitle?: string | null;
3712
+ } & {
3713
+ [key: string]: unknown;
3708
3714
  };
3709
3715
  /** PublicStatus */
3710
3716
  PublicStatus: {
@@ -5066,6 +5072,8 @@ declare interface components {
5066
5072
  };
5067
5073
  /** UserUpdateInput */
5068
5074
  UserUpdateInput: {
5075
+ /** Current Password */
5076
+ current_password?: string | null;
5069
5077
  /** Email */
5070
5078
  email?: string | null;
5071
5079
  /** Metadata */
@@ -5341,7 +5349,7 @@ export declare type EntitlementWindow = Schemas['QuotaWindow'];
5341
5349
  /**
5342
5350
  * Evaluates a condition against the current metadata state.
5343
5351
  */
5344
- export declare function evaluateCondition(condition: MetadataFieldCondition | undefined, metadata: Record<string, any>): boolean;
5352
+ export declare function evaluateCondition(condition: MetadataFieldCondition | undefined, metadata: Record<string, unknown>): boolean;
5345
5353
 
5346
5354
  /** Response from the feedback endpoint. */
5347
5355
  export declare type FeedbackResponse = Schemas['StatusResponse'];
@@ -12690,6 +12698,7 @@ declare interface paths {
12690
12698
  put?: never;
12691
12699
  /**
12692
12700
  * Authorize User
12701
+ * @deprecated
12693
12702
  * @description Authorize or register a user by an enabled login field (default: username), or by
12694
12703
  * ``external_id``, and return a JWT. Protected by an API key.
12695
12704
  *
@@ -328,6 +328,8 @@ declare function buildApi(http: HttpClient, auth: ResolvedAuthAdapter, options:
328
328
  week_start?: ("monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday") | null;
329
329
  welcome_greeting?: string | null;
330
330
  welcome_subtitle?: string | null;
331
+ } & {
332
+ [key: string]: unknown;
331
333
  }>;
332
334
  /** Whether the service is under maintenance. Public; polled by `useGentiqStatus`. */
333
335
  getStatus: (signal?: AbortSignal) => Promise<{
@@ -731,6 +733,8 @@ export declare interface ChatRuntime {
731
733
  subscribeThreads: (listener: () => void) => () => void;
732
734
  /** Call `listener` on each of the runtime's events. Returns a function that stops listening. */
733
735
  onEvent: (listener: (event: ChatRuntimeEvent) => void) => () => void;
736
+ /** Stops every turn and lets go of every controller and attachment URL while keeping subscribers. */
737
+ reset: () => void;
734
738
  /** Stops every turn and lets go of every controller and attachment URL. */
735
739
  dispose: () => void;
736
740
  }
@@ -1577,7 +1581,7 @@ export declare interface components {
1577
1581
  /** Surname */
1578
1582
  surname: string | null;
1579
1583
  /** Token */
1580
- token: string;
1584
+ token?: string | null;
1581
1585
  /** Username */
1582
1586
  username: string | null;
1583
1587
  };
@@ -1619,7 +1623,7 @@ export declare interface components {
1619
1623
  /** Surname */
1620
1624
  surname: string | null;
1621
1625
  /** Token */
1622
- token: string;
1626
+ token?: string | null;
1623
1627
  /**
1624
1628
  * Type
1625
1629
  * @enum {string}
@@ -1633,6 +1637,8 @@ export declare interface components {
1633
1637
  * @description An admin's edit of a user. Unlike a user's edit of themselves, it can set the user's group.
1634
1638
  */
1635
1639
  AdminUserUpdateInput: {
1640
+ /** Current Password */
1641
+ current_password?: string | null;
1636
1642
  /** Email */
1637
1643
  email?: string | null;
1638
1644
  /** Metadata */
@@ -3731,6 +3737,8 @@ export declare interface components {
3731
3737
  welcome_greeting?: string | null;
3732
3738
  /** Welcome Subtitle */
3733
3739
  welcome_subtitle?: string | null;
3740
+ } & {
3741
+ [key: string]: unknown;
3734
3742
  };
3735
3743
  /** PublicStatus */
3736
3744
  PublicStatus: {
@@ -5092,6 +5100,8 @@ export declare interface components {
5092
5100
  };
5093
5101
  /** UserUpdateInput */
5094
5102
  UserUpdateInput: {
5103
+ /** Current Password */
5104
+ current_password?: string | null;
5095
5105
  /** Email */
5096
5106
  email?: string | null;
5097
5107
  /** Metadata */
@@ -5300,6 +5310,8 @@ declare interface ComposerDrafts {
5300
5310
  addVoiceInput: (scope: string, id: string) => void;
5301
5311
  /** Empties the scope and returns what it held, as when a message is sent. */
5302
5312
  take: (scope: string) => ComposerDraft;
5313
+ /** Clears every scope, as when signing out or disposing the runtime. */
5314
+ clear: () => void;
5303
5315
  }
5304
5316
 
5305
5317
  /** A file attached to the message being drafted. */
@@ -5333,6 +5345,8 @@ declare interface ComposerFiles {
5333
5345
  retry: (scope: string, key: string) => void;
5334
5346
  /** Takes every file out of the scope and returns what was there, as when a message is sent. */
5335
5347
  take: (scope: string) => readonly ComposerFile[];
5348
+ /** Cancels every in-flight upload and clears all scopes. */
5349
+ clear: () => void;
5336
5350
  }
5337
5351
 
5338
5352
  /** Where a file attached in the composer is on its way to the server. */
@@ -12634,6 +12648,7 @@ declare interface paths {
12634
12648
  put?: never;
12635
12649
  /**
12636
12650
  * Authorize User
12651
+ * @deprecated
12637
12652
  * @description Authorize or register a user by an enabled login field (default: username), or by
12638
12653
  * ``external_id``, and return a JWT. Protected by an API key.
12639
12654
  *
@@ -1,7 +1,7 @@
1
- import { createAttachmentCache as k } from "../attachments/attachmentCache.es.js";
1
+ import { createAttachmentCache as y } from "../attachments/attachmentCache.es.js";
2
2
  import { isTurnActive as T } from "./threadReducer.es.js";
3
3
  import { createThreadController as w } from "./threadController.es.js";
4
- const x = 3e4, C = 8, g = [];
4
+ const x = 3e4, C = 8, S = [];
5
5
  function N({
6
6
  http: A,
7
7
  resolveAttachment: D,
@@ -9,70 +9,70 @@ function N({
9
9
  getRunOptions: M,
10
10
  now: u = Date.now
11
11
  }) {
12
- const _ = k(D), c = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set();
13
- let o, a = g;
14
- const m = (e) => d.forEach((t) => t(e)), f = /* @__PURE__ */ new Set(), h = () => f.forEach((e) => e());
15
- function b() {
12
+ const _ = y(D), c = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set();
13
+ let o, a = S;
14
+ const m = (e) => f.forEach((t) => t(e)), h = /* @__PURE__ */ new Set(), d = () => h.forEach((e) => e());
15
+ function v() {
16
16
  const e = [...c].filter(([, t]) => T(t.controller.getState())).map(([t]) => t).sort();
17
- e.length === a.length && e.every((t, n) => t === a[n]) || (a = e.length === 0 ? g : e, l.forEach((t) => t()));
17
+ e.length === a.length && e.every((t, r) => t === a[r]) || (a = e.length === 0 ? S : e, l.forEach((t) => t()));
18
18
  }
19
- function v(e, t) {
20
- const n = {
19
+ function E(e, t) {
20
+ const r = {
21
21
  controller: t,
22
22
  idleSince: u(),
23
- unsubscribe: t.subscribe(b)
23
+ unsubscribe: t.subscribe(v)
24
24
  };
25
- return c.set(e, n), h(), b(), n;
25
+ return c.set(e, r), d(), v(), r;
26
26
  }
27
- function E(e) {
27
+ function b(e) {
28
28
  const t = w({
29
29
  http: A,
30
30
  attachments: _,
31
31
  threadId: e,
32
32
  throttleMs: L,
33
33
  getRunOptions: M,
34
- onStart: (n, r) => {
35
- o === t && (o = void 0), v(n, t), m({ type: "thread-started", threadId: n, message: r });
34
+ onStart: (r, n) => {
35
+ o === t && (o = void 0), E(r, t), m({ type: "thread-started", threadId: r, message: n });
36
36
  },
37
- onTurnEnd: (n) => {
38
- const r = c.get(n.threadId);
39
- r && (r.idleSince = u()), m({ type: "turn-ended", ...n }), S();
37
+ onTurnEnd: (r) => {
38
+ const n = c.get(r.threadId);
39
+ n && (n.idleSince = u()), m({ type: "turn-ended", ...r }), g();
40
40
  }
41
41
  });
42
42
  return t;
43
43
  }
44
- function y(e) {
45
- return (i.get(e.controller) ?? 0) === 0 && !T(e.controller.getState());
44
+ function k(e) {
45
+ return (s.get(e.controller) ?? 0) === 0 && !T(e.controller.getState());
46
46
  }
47
47
  function p(e, t) {
48
- c.delete(e), t.unsubscribe(), t.controller.dispose(), h();
48
+ c.delete(e), t.unsubscribe(), t.controller.dispose(), d();
49
49
  }
50
- function S() {
51
- const e = [...c].filter(([, r]) => y(r)), t = u() - x, n = e.filter(([r, s]) => s.idleSince > t ? !0 : (p(r, s), !1));
52
- n.sort(([, r], [, s]) => r.idleSince - s.idleSince).slice(0, Math.max(0, n.length - C)).forEach(([r, s]) => p(r, s));
50
+ function g() {
51
+ const e = [...c].filter(([, n]) => k(n)), t = u() - x, r = e.filter(([n, i]) => i.idleSince > t ? !0 : (p(n, i), !1));
52
+ r.sort(([, n], [, i]) => n.idleSince - i.idleSince).slice(0, Math.max(0, r.length - C)).forEach(([n, i]) => p(n, i));
53
53
  }
54
54
  return {
55
55
  thread(e) {
56
56
  if (e === null)
57
- return o || (o = E(null), h()), o;
58
- const t = c.get(e)?.controller ?? v(e, E(e)).controller;
59
- return S(), t;
57
+ return o || (o = b(null), d()), o;
58
+ const t = c.get(e)?.controller ?? E(e, b(e)).controller;
59
+ return g(), t;
60
60
  },
61
61
  peek: (e) => e === null ? o : c.get(e)?.controller,
62
62
  hold(e) {
63
- i.set(e, (i.get(e) ?? 0) + 1);
63
+ s.set(e, (s.get(e) ?? 0) + 1);
64
64
  let t = !1;
65
65
  return () => {
66
66
  if (t) return;
67
67
  t = !0;
68
- const n = (i.get(e) ?? 1) - 1;
69
- if (n > 0) {
70
- i.set(e, n);
68
+ const r = (s.get(e) ?? 1) - 1;
69
+ if (r > 0) {
70
+ s.set(e, r);
71
71
  return;
72
72
  }
73
- i.delete(e);
74
- const r = [...c.values()].find((s) => s.controller === e);
75
- r && (r.idleSince = u()), S();
73
+ s.delete(e);
74
+ const n = [...c.values()].find((i) => i.controller === e);
75
+ n && (n.idleSince = u()), g();
76
76
  };
77
77
  },
78
78
  getActiveThreadIds: () => a,
@@ -82,18 +82,22 @@ function N({
82
82
  };
83
83
  },
84
84
  subscribeThreads(e) {
85
- return f.add(e), () => {
86
- f.delete(e);
85
+ return h.add(e), () => {
86
+ h.delete(e);
87
87
  };
88
88
  },
89
89
  onEvent(e) {
90
- return d.add(e), () => {
91
- d.delete(e);
90
+ return f.add(e), () => {
91
+ f.delete(e);
92
92
  };
93
93
  },
94
+ reset() {
95
+ for (const [e, t] of c) p(e, t);
96
+ o?.dispose(), o = void 0, s.clear(), a = S, l.forEach((e) => e()), d();
97
+ },
94
98
  dispose() {
95
99
  for (const [e, t] of c) p(e, t);
96
- o?.dispose(), o = void 0, i.clear(), d.clear(), a = g, l.forEach((e) => e()), l.clear(), h(), f.clear();
100
+ o?.dispose(), o = void 0, s.clear(), f.clear(), a = S, l.forEach((e) => e()), l.clear(), d(), h.clear();
97
101
  }
98
102
  };
99
103
  }
@@ -1,48 +1,53 @@
1
- import { DefaultChatTransport as m } from "ai";
2
- import { errorFromResponse as d } from "../client/http.es.js";
3
- import { answersRequestBody as q, chatRequestBody as l } from "../protocol/chatRequest.es.js";
4
- import { startTrace as w, logRequestFailed as y, markReported as R, logRequestRefused as C, monitorChatResponse as T } from "./chatDiagnostics.es.js";
5
- function x(n, r, {
1
+ import { DefaultChatTransport as d } from "ai";
2
+ import { errorFromResponse as l } from "../client/http.es.js";
3
+ import { answersRequestBody as q, chatRequestBody as w } from "../protocol/chatRequest.es.js";
4
+ import { startTrace as y, logRequestFailed as g, markReported as R, logRequestRefused as C, monitorChatResponse as T } from "./chatDiagnostics.es.js";
5
+ function B(n, r, {
6
6
  lastRequest: c,
7
7
  toolOutputs: h = [],
8
8
  runOptions: u,
9
- resume: p
9
+ resume: p,
10
+ abortSignal: i
10
11
  }) {
11
- return new m({
12
+ return new d({
12
13
  api: "/chat",
13
14
  // The server holds the thread's history, so only the message being sent goes, or, when the
14
15
  // last message is an answer, the user's answers to the tool calls it waits on.
15
- prepareSendMessagesRequest: ({ messages: a }) => {
16
- const s = a.at(-1);
16
+ prepareSendMessagesRequest: ({ messages: s }) => {
17
+ const o = s.at(-1);
17
18
  return {
18
- body: s?.role === "assistant" ? q(r, s, { toolOutputs: h, options: u }) : l(r, a, u)
19
+ body: o?.role === "assistant" ? q(r, o, { toolOutputs: h, options: u }) : w(r, s, u)
19
20
  };
20
21
  },
21
22
  prepareReconnectToStreamRequest: () => ({
22
- api: p ? g(r, p.turnId, p.after) : "/chat"
23
+ api: p ? S(r, p.turnId, p.after) : "/chat"
23
24
  }),
24
25
  // The transport passes one of the paths above.
25
- fetch: async (a, s) => {
26
- const i = typeof a == "string" ? a : "/chat", f = new Headers(s?.headers), o = w(r);
27
- c.trace = o, f.set("X-Request-ID", o.requestId);
26
+ fetch: async (s, o) => {
27
+ const m = typeof s == "string" ? s : "/chat", f = new Headers(o?.headers), a = y(r);
28
+ c.trace = a, f.set("X-Request-ID", a.requestId);
28
29
  let t;
29
30
  try {
30
- t = await n.fetch(i, { ...s, headers: f });
31
+ t = await n.fetch(m, {
32
+ ...o,
33
+ signal: i ?? o?.signal,
34
+ headers: f
35
+ });
31
36
  } catch (e) {
32
- throw y(o, e), e instanceof Error ? R(e) : e;
37
+ throw g(a, e), e instanceof Error ? R(e) : e;
33
38
  }
34
39
  if (!t.ok) {
35
- o.status = t.status;
40
+ a.status = t.status;
36
41
  const e = await t.text().catch(() => "");
37
- throw C(o, t, e), R(d(t, e));
42
+ throw C(a, t, e), R(l(t, e));
38
43
  }
39
- return T(o, t);
44
+ return T(a, t);
40
45
  }
41
46
  });
42
47
  }
43
- function g(n, r, c) {
48
+ function S(n, r, c) {
44
49
  return `/chat/threads/${encodeURIComponent(n)}/turns/${encodeURIComponent(r)}/stream?after=${c}`;
45
50
  }
46
51
  export {
47
- x as createChatTransport
52
+ B as createChatTransport
48
53
  };
@@ -1,19 +1,19 @@
1
- import { generateId as z, readUIMessageStream as st } from "ai";
2
- import { nanoid as at } from "nanoid";
3
- import { isGentiqError as ot, GentiqErrorCode as U, GentiqError as it } from "../errors.es.js";
4
- import { isAwaitingOutput as dt, isAwaitingApproval as ut, resolveMessageId as N, messageFeedback as B, isAwaitingUser as lt, attachmentFilePart as J } from "../protocol/messages.es.js";
1
+ import { generateId as z, readUIMessageStream as at } from "ai";
2
+ import { nanoid as it } from "nanoid";
3
+ import { isGentiqError as $, GentiqErrorCode as C, GentiqError as ot } from "../errors.es.js";
4
+ import { isAwaitingOutput as ut, isAwaitingApproval as dt, resolveMessageId as U, messageFeedback as B, isAwaitingUser as lt, attachmentFilePart as J } from "../protocol/messages.es.js";
5
5
  import { toGentiqMessages as K } from "../protocol/storedMessages.es.js";
6
6
  import { logDisconnected as ct, logChatError as ft } from "./chatDiagnostics.es.js";
7
7
  import { createChatTransport as Q } from "./chatTransport.es.js";
8
8
  import { shareUnchanged as pt } from "./shareUnchanged.es.js";
9
9
  import { isTurnActive as yt, newThreadState as mt, storedThreadState as gt, threadReducer as ht } from "./threadReducer.es.js";
10
10
  const V = 50, W = [250, 500, 1e3, 2e3, 4e3, 8e3];
11
- function Nt({
11
+ function Ut({
12
12
  http: n,
13
- attachments: u,
13
+ attachments: o,
14
14
  threadId: b,
15
15
  throttleMs: f = 0,
16
- onStart: C,
16
+ onStart: O,
17
17
  onTurnEnd: x,
18
18
  getRunOptions: T
19
19
  }) {
@@ -22,7 +22,7 @@ function Nt({
22
22
  let A;
23
23
  const k = /* @__PURE__ */ new Set();
24
24
  let E, G = 0;
25
- const O = /* @__PURE__ */ new Map();
25
+ const P = /* @__PURE__ */ new Map();
26
26
  let c = !1, I, v;
27
27
  function l(t) {
28
28
  const e = ht(s, t);
@@ -33,32 +33,33 @@ function Nt({
33
33
  const { turn: t, message: e } = I;
34
34
  I = void 0, l({ type: "reply", turn: t, message: e });
35
35
  }
36
- function tt(t, e) {
36
+ function et(t, e) {
37
37
  if (f <= 0) return l({ type: "reply", turn: t, message: e });
38
38
  I = { turn: t, message: e }, v === void 0 && (S(), v = setTimeout(function r() {
39
39
  v = void 0, I && (S(), v = setTimeout(r, f));
40
40
  }, f));
41
41
  }
42
- async function L(t) {
43
- return _.push(t), u.acquire(t);
42
+ async function M(t) {
43
+ return _.push(t), o.acquire(t);
44
44
  }
45
- function M(t) {
46
- t.forEach((e) => u.release(e));
45
+ function L(t) {
46
+ t.forEach((e) => o.release(e));
47
47
  }
48
- async function et(t) {
49
- return t.file ? (_.push(t.id), J(t, u.adopt(t.id, t.file))) : J(t, await L(t.id));
48
+ async function rt(t) {
49
+ return t.file ? (_.push(t.id), J(t, o.adopt(t.id, t.file))) : J(t, await M(t.id));
50
50
  }
51
- function F(t, e, r, a) {
51
+ function F(t, e, r, a, i) {
52
52
  return Q(n, t, {
53
53
  lastRequest: a,
54
- resume: { turnId: e, after: r }
54
+ resume: { turnId: e, after: r },
55
+ abortSignal: i
55
56
  }).reconnectToStream({ chatId: t });
56
57
  }
57
- function rt(t, e, {
58
+ function nt(t, e, {
58
59
  turnId: r,
59
60
  signal: a,
60
- lastRequest: o,
61
- onTurn: i
61
+ lastRequest: i,
62
+ onTurn: u
62
63
  }) {
63
64
  let d = r, m = 0, p = e.getReader();
64
65
  return new ReadableStream({
@@ -67,16 +68,16 @@ function Nt({
67
68
  for (; ; )
68
69
  try {
69
70
  const { done: g, value: h } = await p.read();
70
- return g ? y.close() : (m += 1, h.type === "data-turn" && Et(h.data) && (d = h.data.turn_id, i(d)), y.enqueue(h));
71
+ return g ? y.close() : (m += 1, h.type === "data-turn" && Et(h.data) && (d = h.data.turn_id, u(d)), y.enqueue(h));
71
72
  } catch (g) {
72
73
  if (a.aborted || d === void 0 || !D(g) || w >= W.length) throw g;
73
74
  await It(W[w], a), w += 1;
74
75
  try {
75
- const h = await F(t, d, m, o);
76
+ const h = await F(t, d, m, i, a);
76
77
  if (!h) return y.close();
77
78
  p = h.getReader();
78
79
  } catch (h) {
79
- if (a.aborted || !D(h)) throw h;
80
+ if (a.aborted || !Rt(h)) throw h;
80
81
  }
81
82
  }
82
83
  },
@@ -86,18 +87,18 @@ function Nt({
86
87
  });
87
88
  }
88
89
  async function R(t, e, { start: r = !1, resume: a } = {}) {
89
- const o = a ? [] : [...O.values()];
90
- a || O.clear(), G += 1;
91
- const i = G, d = new AbortController(), m = { turn: i, abort: d, threadId: t, turnId: a };
90
+ const i = a ? [] : [...P.values()];
91
+ a || P.clear(), G += 1;
92
+ const u = G, d = new AbortController(), m = { turn: u, abort: d, threadId: t, turnId: a };
92
93
  E = m, l(
93
- r ? { type: "start", threadId: t, messages: e, turn: i } : { type: "send", messages: e, turn: i }
94
+ r ? { type: "start", threadId: t, messages: e, turn: u } : { type: "send", messages: e, turn: u }
94
95
  );
95
96
  const p = {};
96
97
  let y, w;
97
98
  try {
98
- const g = a ? await F(t, a, 0, p) : await Q(n, t, {
99
+ const g = a ? await F(t, a, 0, p, d.signal) : await Q(n, t, {
99
100
  lastRequest: p,
100
- toolOutputs: o,
101
+ toolOutputs: i,
101
102
  runOptions: T?.()
102
103
  }).sendMessages({
103
104
  trigger: "submit-message",
@@ -105,28 +106,28 @@ function Nt({
105
106
  messageId: void 0,
106
107
  messages: [...e],
107
108
  abortSignal: d.signal
108
- }), h = rt(t, g ?? Tt(), {
109
+ }), h = nt(t, g ?? Tt(), {
109
110
  turnId: a,
110
111
  signal: d.signal,
111
112
  lastRequest: p,
112
- onTurn: (P) => {
113
- m.turnId = P;
113
+ onTurn: (N) => {
114
+ m.turnId = N;
114
115
  }
115
- }), Y = e.at(-1), nt = st({
116
+ }), Y = e.at(-1), st = at({
116
117
  message: Y?.role === "assistant" ? wt(Y) : { id: z(), role: "assistant", parts: [] },
117
118
  stream: h,
118
119
  terminateOnError: !0
119
120
  });
120
- for await (const P of nt) {
121
- if (d.signal.aborted) break;
122
- const Z = pt(y, P);
123
- y = Z, tt(i, Z);
121
+ for await (const N of st) {
122
+ if (d.signal.aborted) continue;
123
+ const Z = pt(y, N);
124
+ y = Z, et(u, Z);
124
125
  }
125
126
  w = d.signal.aborted ? { outcome: "stopped" } : { outcome: "finished" };
126
127
  } catch (g) {
127
128
  d.signal.aborted || g instanceof Error && g.name === "AbortError" ? w = { outcome: "stopped" } : (D(g) && ct(p.trace), g instanceof Error && ft(p.trace, g), w = { outcome: "failed", error: vt(g) });
128
129
  }
129
- E?.turn === i && (E = void 0), I?.turn === i && S(), w.outcome === "failed" ? l({ type: "fail", turn: i, error: w.error }) : l({ type: w.outcome === "stopped" ? "stop" : "finish", turn: i }), c || x?.({ threadId: t, ...w, reply: y, ...Rt(y) });
130
+ E?.turn === u && (E = void 0), I?.turn === u && S(), w.outcome === "failed" ? l({ type: "fail", turn: u, error: w.error }) : l({ type: w.outcome === "stopped" ? "stop" : "finish", turn: u }), c || x?.({ threadId: t, ...w, reply: y, ..._t(y) });
130
131
  }
131
132
  async function j() {
132
133
  if (s.status !== "ready" && s.status !== "error") return;
@@ -152,15 +153,15 @@ function Nt({
152
153
  signal: e.signal
153
154
  });
154
155
  if (e.signal.aborted) return;
155
- const a = r.turn?.status === "failed" ? $(r.turn) : void 0;
156
+ const a = r.turn?.status === "failed" ? tt(r.turn) : void 0;
156
157
  l({
157
158
  type: "loaded",
158
159
  messages: K(r.items),
159
160
  cursor: r.next_cursor,
160
161
  ...a ? { error: a } : {}
161
162
  });
162
- const o = H.getState();
163
- r.turn?.status === "running" && o.status === "ready" && R(t, o.messages, { resume: r.turn.id });
163
+ const i = H.getState();
164
+ r.turn?.status === "running" && i.status === "ready" && R(t, i.messages, { resume: r.turn.id });
164
165
  } catch (r) {
165
166
  e.signal.aborted || l({ type: "load-failed", error: r });
166
167
  } finally {
@@ -186,17 +187,17 @@ function Nt({
186
187
  }
187
188
  },
188
189
  loadAttachment(t) {
189
- c || k.has(t) || (k.add(t), L(t).then((e) => {
190
+ c || k.has(t) || (k.add(t), M(t).then((e) => {
190
191
  !c && e && l({ type: "attachment", attachmentId: t, url: e }), e || k.delete(t);
191
192
  }));
192
193
  },
193
194
  async send({ text: t, attachments: e = [], references: r = [], voiceInputs: a = [] }) {
194
195
  if (!X(s) || c) return;
195
- const o = t.trim();
196
- if (!o && e.length === 0 && r.length === 0) return;
197
- const i = _.length, d = await Promise.all(e.map(et));
196
+ const i = t.trim();
197
+ if (!i && e.length === 0 && r.length === 0) return;
198
+ const u = _.length, d = await Promise.all(e.map(rt));
198
199
  if (!X(s) || c) {
199
- M(_.splice(i));
200
+ L(_.splice(u));
200
201
  return;
201
202
  }
202
203
  const m = {
@@ -208,91 +209,91 @@ function Nt({
208
209
  parts: [
209
210
  ...r.map((y) => ({ type: "data-reference", data: y })),
210
211
  ...d,
211
- { type: "text", text: o }
212
+ { type: "text", text: i }
212
213
  ],
213
214
  ...Object.keys(m).length > 0 ? { metadata: m } : {}
214
215
  };
215
216
  if (s.status === "new") {
216
- const y = at();
217
- return C?.(y, p), R(y, [p], { start: !0 });
217
+ const y = it();
218
+ return O?.(y, p), R(y, [p], { start: !0 });
218
219
  }
219
220
  return R(s.threadId, [...s.messages, p]);
220
221
  },
221
222
  async retry(t) {
222
223
  if (c || s.status !== "ready" && s.status !== "error") return;
223
224
  const { messages: e, threadId: r } = s, a = e.findIndex(
224
- (i) => i.role === "assistant" && (i.id === t || N(i) === t)
225
+ (u) => u.role === "assistant" && (u.id === t || U(u) === t)
225
226
  );
226
227
  if (a === -1) return;
227
- let o = a - 1;
228
- for (; o >= 0 && e[o].role !== "user"; ) o -= 1;
229
- if (o !== -1)
230
- return R(r, e.slice(0, o + 1));
228
+ let i = a - 1;
229
+ for (; i >= 0 && e[i].role !== "user"; ) i -= 1;
230
+ if (i !== -1)
231
+ return R(r, e.slice(0, i + 1));
231
232
  },
232
233
  async edit(t, { text: e }) {
233
234
  if (c || s.status !== "ready" && s.status !== "error") return;
234
- const { messages: r, threadId: a } = s, o = r.findIndex(
235
+ const { messages: r, threadId: a } = s, i = r.findIndex(
235
236
  (m) => m.role === "user" && m.id === t
236
237
  );
237
- if (o === -1) return;
238
- const i = bt(r[o].parts, e.trim());
239
- if (i.length === 0) return;
240
- const d = { ...r[o], parts: i };
241
- return R(a, [...r.slice(0, o), d]);
238
+ if (i === -1) return;
239
+ const u = bt(r[i].parts, e.trim());
240
+ if (u.length === 0) return;
241
+ const d = { ...r[i], parts: u };
242
+ return R(a, [...r.slice(0, i), d]);
242
243
  },
243
244
  async setFeedback(t, e) {
244
245
  const { threadId: r } = s;
245
246
  if (c || r === null) return;
246
247
  const a = s.messages.find(
247
- (d) => d.role === "assistant" && (d.id === t || N(d) === t)
248
+ (d) => d.role === "assistant" && (d.id === t || U(d) === t)
248
249
  );
249
250
  if (!a) return;
250
- const o = B(a), i = e ?? void 0;
251
- l({ type: "feedback", messageId: a.id, feedback: i });
251
+ const i = B(a), u = e ?? void 0;
252
+ l({ type: "feedback", messageId: a.id, feedback: u });
252
253
  try {
253
254
  await n.request("post", "/chat/feedback", {
254
- body: { thread_id: r, message_id: N(a), sentiment: e }
255
+ body: { thread_id: r, message_id: U(a), sentiment: e }
255
256
  });
256
257
  } catch (d) {
257
258
  const m = s.messages.find((p) => p.id === a.id);
258
- throw m && B(m) === i && l({ type: "feedback", messageId: a.id, feedback: o }), d;
259
+ throw m && B(m) === u && l({ type: "feedback", messageId: a.id, feedback: i }), d;
259
260
  }
260
261
  },
261
262
  async addToolApprovalResponse(t) {
262
- if (!(c || s.status !== "ready" && s.status !== "error" || !s.messages.at(-1)?.parts.some((r) => ut(r, t.id))))
263
+ if (!(c || s.status !== "ready" && s.status !== "error" || !s.messages.at(-1)?.parts.some((r) => dt(r, t.id))))
263
264
  return l({ type: "approval", response: t }), j();
264
265
  },
265
266
  async addToolOutput(t) {
266
- if (!(c || s.status !== "ready" && s.status !== "error" || !s.messages.at(-1)?.parts.some((r) => dt(r, t.toolCallId))))
267
- return O.set(t.toolCallId, t), l({ type: "tool-output", response: t }), j();
267
+ if (!(c || s.status !== "ready" && s.status !== "error" || !s.messages.at(-1)?.parts.some((r) => ut(r, t.toolCallId))))
268
+ return P.set(t.toolCallId, t), l({ type: "tool-output", response: t }), j();
268
269
  },
269
270
  stop() {
270
271
  if (!E || !yt(s)) return;
271
272
  const { turn: t, abort: e, threadId: r } = E;
272
273
  E = void 0, e.abort(), I?.turn === t && S(), l({ type: "stop", turn: t }), n.request("post", "/chat/threads/{thread_id}/stop", { path: { thread_id: r } }).catch((a) => {
273
- ot(a) && a.status === 404 || c || l({ type: "stop-failed", error: a });
274
+ $(a) && a.status === 404 || c || l({ type: "stop-failed", error: a });
274
275
  });
275
276
  },
276
277
  dismissError() {
277
278
  l({ type: "dismiss-error" });
278
279
  },
279
280
  dispose() {
280
- c || (c = !0, A?.abort(), E?.abort.abort(), E = void 0, clearTimeout(v), q.clear(), M(_.splice(0)));
281
+ c || (c = !0, A?.abort(), E?.abort.abort(), E = void 0, clearTimeout(v), q.clear(), L(_.splice(0)));
281
282
  }
282
283
  };
283
284
  return H;
284
285
  }
285
- function bt(n, u) {
286
+ function bt(n, o) {
286
287
  const b = n.findIndex((T) => T.type === "text"), f = n.filter((T) => T.type !== "text");
287
- if (!u) return f;
288
- const C = { type: "text", text: u }, x = b === -1 ? f.length : n.slice(0, b).filter((T) => T.type !== "text").length;
289
- return [...f.slice(0, x), C, ...f.slice(x)];
288
+ if (!o) return f;
289
+ const O = { type: "text", text: o }, x = b === -1 ? f.length : n.slice(0, b).filter((T) => T.type !== "text").length;
290
+ return [...f.slice(0, x), O, ...f.slice(x)];
290
291
  }
291
292
  function wt(n) {
292
293
  return {
293
294
  ...n,
294
295
  parts: n.parts.filter(
295
- (u) => u.type !== "data-chat-finished" && u.type !== "data-title"
296
+ (o) => o.type !== "data-chat-finished" && o.type !== "data-title"
296
297
  )
297
298
  };
298
299
  }
@@ -305,33 +306,36 @@ function Et(n) {
305
306
  function Tt() {
306
307
  return new ReadableStream({ start: (n) => n.close() });
307
308
  }
308
- function It(n, u) {
309
+ function It(n, o) {
309
310
  return new Promise((b) => {
310
311
  const f = setTimeout(b, n);
311
- u.addEventListener("abort", () => {
312
+ o.addEventListener("abort", () => {
312
313
  clearTimeout(f), b();
313
314
  });
314
315
  });
315
316
  }
316
317
  function vt(n) {
317
- return n instanceof Error && n.message === U.TURN_INTERRUPTED ? $({ error: U.TURN_INTERRUPTED }) : n;
318
+ return n instanceof Error && n.message === C.TURN_INTERRUPTED ? tt({ error: C.TURN_INTERRUPTED }) : n;
318
319
  }
319
- function $(n) {
320
- const u = n.error ?? U.INTERNAL_ERROR;
321
- return new it({ error: { code: u, message: "The turn broke off." } });
320
+ function tt(n) {
321
+ const o = n.error ?? C.INTERNAL_ERROR;
322
+ return new ot({ error: { code: o, message: "The turn broke off." } });
322
323
  }
323
324
  function D(n) {
324
325
  if (!(n instanceof TypeError)) return !1;
325
- const u = n.message.toLowerCase();
326
- return u.includes("fetch") || u.includes("network");
326
+ const o = n.message.toLowerCase();
327
+ return o.includes("fetch") || o.includes("network") || o.includes("load failed") || o.includes("stream");
327
328
  }
328
329
  function Rt(n) {
329
- let u, b = !1;
330
+ return D(n) ? !0 : $(n) ? n.code === C.TIMEOUT || n.status === 502 || n.status === 503 || n.status === 504 : !1;
331
+ }
332
+ function _t(n) {
333
+ let o, b = !1;
330
334
  for (const f of n?.parts ?? [])
331
- f.type === "data-title" && f.data.title && (u = f.data.title), f.type === "data-chat-finished" && f.data.title_pending && (b = !0);
332
- return { ...u ? { title: u } : {}, titlePending: b };
335
+ f.type === "data-title" && f.data.title && (o = f.data.title), f.type === "data-chat-finished" && f.data.title_pending && (b = !0);
336
+ return { ...o ? { title: o } : {}, titlePending: b };
333
337
  }
334
338
  export {
335
339
  V as THREAD_PAGE_SIZE,
336
- Nt as createThreadController
340
+ Ut as createThreadController
337
341
  };
package/package.json CHANGED
@@ -11,7 +11,8 @@
11
11
  "provenance": false
12
12
  },
13
13
  "description": "Framework-free core of the Gentiq SDK: the API client, the chat protocol and the thread controller.",
14
- "version": "1.0.0-alpha.12",
14
+ "version": "1.0.0-alpha.14",
15
+ "license": "Apache-2.0",
15
16
  "type": "module",
16
17
  "files": [
17
18
  "dist"