@witqq/agent-sdk 0.7.0 → 0.8.0

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 (147) hide show
  1. package/README.md +140 -34
  2. package/dist/{types-CqvUAYxt.d.cts → agent-CW9XbmG_.d.ts} +137 -102
  3. package/dist/{types-CqvUAYxt.d.ts → agent-DxY68NZL.d.cts} +137 -102
  4. package/dist/auth/index.cjs +72 -1
  5. package/dist/auth/index.cjs.map +1 -1
  6. package/dist/auth/index.d.cts +21 -154
  7. package/dist/auth/index.d.ts +21 -154
  8. package/dist/auth/index.js +72 -1
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/backends/claude.cjs +480 -261
  11. package/dist/backends/claude.cjs.map +1 -1
  12. package/dist/backends/claude.d.cts +3 -1
  13. package/dist/backends/claude.d.ts +3 -1
  14. package/dist/backends/claude.js +480 -261
  15. package/dist/backends/claude.js.map +1 -1
  16. package/dist/backends/copilot.cjs +329 -97
  17. package/dist/backends/copilot.cjs.map +1 -1
  18. package/dist/backends/copilot.d.cts +12 -4
  19. package/dist/backends/copilot.d.ts +12 -4
  20. package/dist/backends/copilot.js +329 -97
  21. package/dist/backends/copilot.js.map +1 -1
  22. package/dist/backends/vercel-ai.cjs +294 -61
  23. package/dist/backends/vercel-ai.cjs.map +1 -1
  24. package/dist/backends/vercel-ai.d.cts +3 -1
  25. package/dist/backends/vercel-ai.d.ts +3 -1
  26. package/dist/backends/vercel-ai.js +294 -61
  27. package/dist/backends/vercel-ai.js.map +1 -1
  28. package/dist/backends-BSrsBYFn.d.cts +39 -0
  29. package/dist/backends-BSrsBYFn.d.ts +39 -0
  30. package/dist/chat/accumulator.cjs +1 -1
  31. package/dist/chat/accumulator.cjs.map +1 -1
  32. package/dist/chat/accumulator.d.cts +5 -2
  33. package/dist/chat/accumulator.d.ts +5 -2
  34. package/dist/chat/accumulator.js +1 -1
  35. package/dist/chat/accumulator.js.map +1 -1
  36. package/dist/chat/backends.cjs +736 -746
  37. package/dist/chat/backends.cjs.map +1 -1
  38. package/dist/chat/backends.d.cts +10 -6
  39. package/dist/chat/backends.d.ts +10 -6
  40. package/dist/chat/backends.js +736 -725
  41. package/dist/chat/backends.js.map +1 -1
  42. package/dist/chat/context.cjs +50 -0
  43. package/dist/chat/context.cjs.map +1 -1
  44. package/dist/chat/context.d.cts +27 -3
  45. package/dist/chat/context.d.ts +27 -3
  46. package/dist/chat/context.js +50 -0
  47. package/dist/chat/context.js.map +1 -1
  48. package/dist/chat/core.cjs +25 -2
  49. package/dist/chat/core.cjs.map +1 -1
  50. package/dist/chat/core.d.cts +30 -381
  51. package/dist/chat/core.d.ts +30 -381
  52. package/dist/chat/core.js +24 -3
  53. package/dist/chat/core.js.map +1 -1
  54. package/dist/chat/errors.cjs +48 -26
  55. package/dist/chat/errors.cjs.map +1 -1
  56. package/dist/chat/errors.d.cts +6 -31
  57. package/dist/chat/errors.d.ts +6 -31
  58. package/dist/chat/errors.js +48 -25
  59. package/dist/chat/errors.js.map +1 -1
  60. package/dist/chat/events.cjs.map +1 -1
  61. package/dist/chat/events.d.cts +6 -2
  62. package/dist/chat/events.d.ts +6 -2
  63. package/dist/chat/events.js.map +1 -1
  64. package/dist/chat/index.cjs +1199 -1008
  65. package/dist/chat/index.cjs.map +1 -1
  66. package/dist/chat/index.d.cts +35 -10
  67. package/dist/chat/index.d.ts +35 -10
  68. package/dist/chat/index.js +1196 -987
  69. package/dist/chat/index.js.map +1 -1
  70. package/dist/chat/react/theme.css +2517 -0
  71. package/dist/chat/react.cjs +2003 -1153
  72. package/dist/chat/react.cjs.map +1 -1
  73. package/dist/chat/react.d.cts +590 -121
  74. package/dist/chat/react.d.ts +590 -121
  75. package/dist/chat/react.js +1984 -1151
  76. package/dist/chat/react.js.map +1 -1
  77. package/dist/chat/runtime.cjs +401 -186
  78. package/dist/chat/runtime.cjs.map +1 -1
  79. package/dist/chat/runtime.d.cts +92 -28
  80. package/dist/chat/runtime.d.ts +92 -28
  81. package/dist/chat/runtime.js +401 -186
  82. package/dist/chat/runtime.js.map +1 -1
  83. package/dist/chat/server.cjs +2234 -209
  84. package/dist/chat/server.cjs.map +1 -1
  85. package/dist/chat/server.d.cts +451 -90
  86. package/dist/chat/server.d.ts +451 -90
  87. package/dist/chat/server.js +2221 -210
  88. package/dist/chat/server.js.map +1 -1
  89. package/dist/chat/sessions.cjs +25 -43
  90. package/dist/chat/sessions.cjs.map +1 -1
  91. package/dist/chat/sessions.d.cts +37 -118
  92. package/dist/chat/sessions.d.ts +37 -118
  93. package/dist/chat/sessions.js +25 -43
  94. package/dist/chat/sessions.js.map +1 -1
  95. package/dist/chat/sqlite.cjs +441 -0
  96. package/dist/chat/sqlite.cjs.map +1 -0
  97. package/dist/chat/sqlite.d.cts +128 -0
  98. package/dist/chat/sqlite.d.ts +128 -0
  99. package/dist/chat/sqlite.js +435 -0
  100. package/dist/chat/sqlite.js.map +1 -0
  101. package/dist/chat/state.cjs +14 -1
  102. package/dist/chat/state.cjs.map +1 -1
  103. package/dist/chat/state.d.cts +5 -2
  104. package/dist/chat/state.d.ts +5 -2
  105. package/dist/chat/state.js +14 -1
  106. package/dist/chat/state.js.map +1 -1
  107. package/dist/chat/storage.cjs +19 -10
  108. package/dist/chat/storage.cjs.map +1 -1
  109. package/dist/chat/storage.d.cts +11 -5
  110. package/dist/chat/storage.d.ts +11 -5
  111. package/dist/chat/storage.js +19 -10
  112. package/dist/chat/storage.js.map +1 -1
  113. package/dist/errors-C-so0M4t.d.cts +33 -0
  114. package/dist/errors-C-so0M4t.d.ts +33 -0
  115. package/dist/errors-CmVvczxZ.d.cts +28 -0
  116. package/dist/errors-CmVvczxZ.d.ts +28 -0
  117. package/dist/{in-process-transport-C2oPTYs6.d.ts → in-process-transport-C1JnJGVR.d.ts} +28 -23
  118. package/dist/{in-process-transport-DG-w5G6k.d.cts → in-process-transport-C7DSqPyX.d.cts} +28 -23
  119. package/dist/index.cjs +340 -46
  120. package/dist/index.cjs.map +1 -1
  121. package/dist/index.d.cts +292 -123
  122. package/dist/index.d.ts +292 -123
  123. package/dist/index.js +334 -47
  124. package/dist/index.js.map +1 -1
  125. package/dist/provider-types-PTSlRPNB.d.cts +39 -0
  126. package/dist/provider-types-PTSlRPNB.d.ts +39 -0
  127. package/dist/refresh-manager-B81PpYBr.d.cts +153 -0
  128. package/dist/refresh-manager-Dlv_iNZi.d.ts +153 -0
  129. package/dist/testing.cjs +383 -0
  130. package/dist/testing.cjs.map +1 -0
  131. package/dist/testing.d.cts +132 -0
  132. package/dist/testing.d.ts +132 -0
  133. package/dist/testing.js +377 -0
  134. package/dist/testing.js.map +1 -0
  135. package/dist/token-store-CSUBgYwn.d.ts +48 -0
  136. package/dist/token-store-CuC4hB9Z.d.cts +48 -0
  137. package/dist/{transport-DX1Nhm4N.d.cts → transport-Cdh3M0tS.d.cts} +5 -4
  138. package/dist/{transport-D1OaUgRk.d.ts → transport-Ciap4PWK.d.ts} +5 -4
  139. package/dist/{types-CGF7AEX1.d.cts → types-4vbcmPTp.d.cts} +4 -2
  140. package/dist/{types-Bh5AhqD-.d.ts → types-BxggH0Yh.d.ts} +4 -2
  141. package/dist/types-DRgd_9R7.d.cts +363 -0
  142. package/dist/types-ajANVzf7.d.ts +363 -0
  143. package/package.json +31 -6
  144. package/dist/errors-BDLbNu9w.d.cts +0 -13
  145. package/dist/errors-BDLbNu9w.d.ts +0 -13
  146. package/dist/types-DLZzlJxt.d.ts +0 -39
  147. package/dist/types-tE0CXwBl.d.cts +0 -39
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var crypto$1 = require('crypto');
3
4
  var fs = require('fs');
4
5
  var path = require('path');
5
6
 
@@ -24,6 +25,101 @@ function _interopNamespace(e) {
24
25
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
25
26
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
26
27
 
28
+ // src/chat/server/utils.ts
29
+ var BodyParseError = class extends Error {
30
+ statusCode;
31
+ constructor(message, statusCode) {
32
+ super(message);
33
+ this.name = "BodyParseError";
34
+ this.statusCode = statusCode;
35
+ }
36
+ };
37
+ function readBody(req, maxSize = 1048576) {
38
+ return new Promise((resolve2, reject) => {
39
+ let body = "";
40
+ let size = 0;
41
+ let exceeded = false;
42
+ req.on("data", (chunk) => {
43
+ if (exceeded) return;
44
+ const str = chunk.toString();
45
+ size += Buffer.byteLength(str);
46
+ if (size > maxSize) {
47
+ exceeded = true;
48
+ reject(new BodyParseError("Request body too large", 413));
49
+ return;
50
+ }
51
+ body += str;
52
+ });
53
+ req.on("end", () => {
54
+ if (exceeded) return;
55
+ try {
56
+ resolve2(JSON.parse(body || "{}"));
57
+ } catch {
58
+ reject(new BodyParseError("Invalid JSON in request body", 400));
59
+ }
60
+ });
61
+ if ("once" in req && typeof req.once === "function") {
62
+ req.once(
63
+ "error",
64
+ () => reject(new BodyParseError("Request error", 500))
65
+ );
66
+ }
67
+ });
68
+ }
69
+ function json(res, data, status = 200) {
70
+ res.writeHead(status, { "Content-Type": "application/json" });
71
+ res.end(JSON.stringify(data));
72
+ }
73
+
74
+ // src/chat/server/routes/sessions.ts
75
+ var sessionRoutes = async (method, path2, req, res, ctx) => {
76
+ const { runtime, maxBodySize } = ctx;
77
+ const sessionMatch = path2.match(/^\/sessions\/([^/]+)$/);
78
+ const contextStatsMatch = path2.match(/^\/sessions\/([^/]+)\/context-stats$/);
79
+ if (method === "POST" && path2 === "/sessions/create") {
80
+ const body = await readBody(req, maxBodySize);
81
+ const session = await runtime.createSession({
82
+ title: body.title || `Chat ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`,
83
+ config: body.config || {
84
+ model: "",
85
+ backend: ""
86
+ },
87
+ ...body.tags ? { tags: body.tags } : {},
88
+ ...body.custom ? { custom: body.custom } : {}
89
+ });
90
+ json(res, session);
91
+ return true;
92
+ }
93
+ if (method === "GET" && contextStatsMatch) {
94
+ const id = decodeURIComponent(contextStatsMatch[1]);
95
+ const stats = await runtime.getContextStats(id);
96
+ json(res, stats ?? null);
97
+ return true;
98
+ }
99
+ if (method === "GET" && sessionMatch) {
100
+ const id = decodeURIComponent(sessionMatch[1]);
101
+ const session = await runtime.getSession(id);
102
+ if (!session) {
103
+ json(res, { error: "Not found" }, 404);
104
+ return true;
105
+ }
106
+ json(res, session);
107
+ return true;
108
+ }
109
+ if (method === "DELETE" && sessionMatch) {
110
+ const id = decodeURIComponent(sessionMatch[1]);
111
+ await runtime.deleteSession(id);
112
+ json(res, { ok: true });
113
+ return true;
114
+ }
115
+ if (method === "GET" && path2 === "/sessions") {
116
+ const sessions = await runtime.listSessions();
117
+ json(res, sessions);
118
+ return true;
119
+ }
120
+ return false;
121
+ };
122
+
27
123
  // src/chat/backends/transport.ts
28
124
  var SSEChatTransport = class {
29
125
  res;
@@ -116,115 +212,332 @@ async function streamToTransport(events, transport) {
116
212
  }
117
213
  }
118
214
 
119
- // src/chat/server/handler.ts
120
- function createChatHandler(runtime, options) {
121
- const prefix = options?.prefix ?? "";
122
- const maxBodySize = options?.maxBodySize ?? 1048576;
123
- const heartbeatMs = options?.heartbeatMs;
124
- return async (req, res) => {
125
- const url = req.url || "";
126
- const method = req.method || "GET";
127
- const rawPath = prefix ? url.slice(prefix.length) : url;
128
- const path2 = rawPath.split("?")[0];
129
- const sessionMatch = path2.match(/^\/sessions\/([^/]+)$/);
130
- const archiveMatch = path2.match(/^\/sessions\/([^/]+)\/archive$/);
131
- try {
132
- if (method === "POST" && path2 === "/sessions/create") {
133
- const body = await readBody(req, maxBodySize);
134
- const session = await runtime.createSession({
135
- title: body.title || `Chat ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`,
136
- config: body.config || {
137
- model: runtime.currentModel || "",
138
- backend: runtime.currentBackend
139
- },
140
- ...body.tags ? { tags: body.tags } : {},
141
- ...body.custom ? { custom: body.custom } : {}
142
- });
143
- json(res, session);
144
- return;
215
+ // src/errors.ts
216
+ var AgentSDKError = class extends Error {
217
+ /** @internal Marker for cross-bundle identity checks */
218
+ _agentSDKError = true;
219
+ /** Machine-readable error code. Prefer values from the ErrorCode enum. */
220
+ code;
221
+ /** Whether this error is safe to retry */
222
+ retryable;
223
+ /** HTTP status code hint for error classification */
224
+ httpStatus;
225
+ constructor(message, options) {
226
+ super(message, options);
227
+ this.name = "AgentSDKError";
228
+ this.code = options?.code;
229
+ this.retryable = options?.retryable ?? false;
230
+ this.httpStatus = options?.httpStatus;
231
+ }
232
+ /** Check if an error is an AgentSDKError (works across bundled copies) */
233
+ static is(error) {
234
+ return error instanceof Error && "_agentSDKError" in error && error._agentSDKError === true;
235
+ }
236
+ };
237
+
238
+ // src/chat/errors.ts
239
+ var ChatError = class extends AgentSDKError {
240
+ code;
241
+ retryable;
242
+ retryAfter;
243
+ timestamp;
244
+ constructor(message, options) {
245
+ super(message, {
246
+ cause: options.cause,
247
+ code: options.code,
248
+ retryable: options.retryable
249
+ });
250
+ this.name = "ChatError";
251
+ this.code = options.code;
252
+ this.retryable = options.retryable ?? false;
253
+ this.retryAfter = options.retryAfter;
254
+ this.timestamp = (/* @__PURE__ */ new Date()).toISOString();
255
+ }
256
+ };
257
+
258
+ // src/chat/server/request-context.ts
259
+ async function resolveRequestContext(providerId, deps) {
260
+ const provider = await deps.providerStore.get(providerId);
261
+ if (!provider) {
262
+ throw new ChatError(`Provider "${providerId}" not found`, {
263
+ code: "PROVIDER_NOT_FOUND" /* PROVIDER_NOT_FOUND */
264
+ });
265
+ }
266
+ const credentials = await deps.tokenStore.load(provider.backend);
267
+ if (!credentials) {
268
+ throw new ChatError(
269
+ `Authentication required for backend "${provider.backend}"`,
270
+ {
271
+ code: "AUTH_REQUIRED" /* AUTH_REQUIRED */
145
272
  }
146
- if (method === "POST" && archiveMatch) {
147
- const id = decodeURIComponent(archiveMatch[1]);
148
- await runtime.archiveSession(id);
149
- json(res, { ok: true });
150
- return;
273
+ );
274
+ }
275
+ return {
276
+ backend: provider.backend,
277
+ credentials,
278
+ model: provider.model,
279
+ provider
280
+ };
281
+ }
282
+
283
+ // src/chat/server/routes/messages.ts
284
+ var messageRoutes = async (method, path2, req, res, ctx) => {
285
+ const { runtime, maxBodySize, heartbeatMs, hooks, transportFactory } = ctx;
286
+ if (method === "POST" && path2 === "/send") {
287
+ const body = await readBody(req, maxBodySize);
288
+ const sessionId = body.sessionId;
289
+ const message = body.message || body.content;
290
+ if (!sessionId || !message) {
291
+ json(res, { error: "sessionId and message are required" }, 400);
292
+ return true;
293
+ }
294
+ let model;
295
+ let reqBackend;
296
+ let reqCredentials;
297
+ const hasProviderInfra = !!(ctx.providerStore && ctx.tokenStore);
298
+ if (hasProviderInfra) {
299
+ const providerId = body.providerId;
300
+ if (!providerId || typeof providerId !== "string") {
301
+ json(res, { error: "providerId is required" }, 400);
302
+ return true;
151
303
  }
152
- if (method === "GET" && sessionMatch) {
153
- const id = decodeURIComponent(sessionMatch[1]);
154
- const session = await runtime.getSession(id);
155
- if (!session) {
156
- json(res, { error: "Not found" }, 404);
157
- return;
304
+ try {
305
+ const reqCtx = await resolveRequestContext(providerId, {
306
+ providerStore: ctx.providerStore,
307
+ tokenStore: ctx.tokenStore
308
+ });
309
+ model = reqCtx.model;
310
+ reqBackend = reqCtx.backend;
311
+ reqCredentials = reqCtx.credentials;
312
+ } catch (err) {
313
+ if (err instanceof ChatError && err.code === "PROVIDER_NOT_FOUND" /* PROVIDER_NOT_FOUND */) {
314
+ json(res, { error: err.message }, 404);
315
+ return true;
158
316
  }
159
- json(res, session);
160
- return;
317
+ if (err instanceof ChatError && err.code === "AUTH_REQUIRED" /* AUTH_REQUIRED */) {
318
+ json(res, { error: err.message }, 401);
319
+ return true;
320
+ }
321
+ throw err;
161
322
  }
162
- if (method === "DELETE" && sessionMatch) {
163
- const id = decodeURIComponent(sessionMatch[1]);
164
- await runtime.deleteSession(id);
165
- json(res, { ok: true });
166
- return;
323
+ }
324
+ const bodyModel = body.model;
325
+ if (hooks?.onModelSwitch && bodyModel && typeof bodyModel === "string") {
326
+ try {
327
+ await hooks.onModelSwitch(bodyModel);
328
+ } catch (err) {
329
+ json(res, { error: err instanceof Error ? err.message : String(err) }, 403);
330
+ return true;
167
331
  }
168
- if (method === "GET" && path2 === "/sessions") {
169
- const sessions = await runtime.listSessions();
170
- json(res, sessions);
171
- return;
332
+ }
333
+ if (hooks?.onBeforeSend) {
334
+ try {
335
+ await hooks.onBeforeSend(sessionId, message);
336
+ } catch (err) {
337
+ json(res, { error: err instanceof Error ? err.message : String(err) }, 403);
338
+ return true;
172
339
  }
173
- if (method === "POST" && path2 === "/send") {
174
- const body = await readBody(req, maxBodySize);
175
- const sessionId = body.sessionId;
176
- const message = body.message || body.content;
177
- if (!sessionId || !message) {
178
- json(res, { error: "sessionId and message are required" }, 400);
179
- return;
180
- }
181
- const transport = new SSEChatTransport(res, {
182
- heartbeatMs,
183
- request: req
184
- });
185
- try {
186
- const opts = {};
187
- if (body.model) opts.model = body.model;
188
- const stream = runtime.send(
189
- sessionId,
190
- message,
191
- Object.keys(opts).length > 0 ? opts : void 0
192
- );
193
- await streamToTransport(stream, transport);
194
- } catch (err) {
195
- transport.error(err instanceof Error ? err : new Error(String(err)));
196
- }
197
- return;
340
+ }
341
+ model = bodyModel || model;
342
+ if (!model) {
343
+ json(res, { error: "model is required (via body.model or providerId)" }, 400);
344
+ return true;
345
+ }
346
+ const transport = transportFactory ? transportFactory(req, res) : new SSEChatTransport(res, {
347
+ heartbeatMs,
348
+ request: req
349
+ });
350
+ try {
351
+ if (!reqBackend || !reqCredentials) {
352
+ json(res, { error: "backend and credentials are required (configure providerStore + tokenStore)" }, 400);
353
+ return true;
198
354
  }
199
- if (method === "POST" && path2 === "/abort") {
200
- runtime.abort();
201
- json(res, { ok: true });
202
- return;
355
+ const opts = { model, backend: reqBackend, credentials: reqCredentials };
356
+ const stream = runtime.send(sessionId, message, opts);
357
+ await streamToTransport(stream, transport);
358
+ } catch (err) {
359
+ transport.error(err instanceof Error ? err : new Error(String(err)));
360
+ }
361
+ return true;
362
+ }
363
+ if (method === "POST" && path2 === "/abort") {
364
+ runtime.abort();
365
+ json(res, { ok: true });
366
+ return true;
367
+ }
368
+ return false;
369
+ };
370
+
371
+ // src/chat/server/routes/config.ts
372
+ var configRoutes = async (method, path2, req, res, ctx) => {
373
+ const { runtime, maxBodySize, hooks, providerStore } = ctx;
374
+ if (method === "GET" && path2 === "/models") {
375
+ let models = await runtime.listModels();
376
+ if (models.length === 0 && providerStore && ctx.tokenStore) {
377
+ const providers = await providerStore.list();
378
+ for (const p of providers) {
379
+ const token = await ctx.tokenStore.load(p.backend);
380
+ if (token) {
381
+ models = await runtime.listModels({ backend: p.backend, credentials: token });
382
+ break;
383
+ }
203
384
  }
204
- if (method === "GET" && path2 === "/models") {
205
- const models = await runtime.listModels();
206
- json(res, models);
207
- return;
385
+ }
386
+ if (hooks?.filterModels) models = hooks.filterModels(models);
387
+ json(res, models);
388
+ return true;
389
+ }
390
+ if (method === "GET" && path2 === "/backends") {
391
+ const backends = await runtime.listBackends();
392
+ json(res, backends);
393
+ return true;
394
+ }
395
+ if (method === "POST" && path2 === "/model/switch") {
396
+ const body = await readBody(req, maxBodySize);
397
+ if (!body.model || typeof body.model !== "string") {
398
+ json(res, { error: "model is required" }, 400);
399
+ return true;
400
+ }
401
+ if (hooks?.onModelSwitch) {
402
+ try {
403
+ await hooks.onModelSwitch(body.model);
404
+ } catch (err) {
405
+ json(res, { error: err instanceof Error ? err.message : String(err) }, 403);
406
+ return true;
208
407
  }
209
- if (method === "POST" && path2 === "/backend/switch") {
210
- const body = await readBody(req, maxBodySize);
211
- if (!body.backend || typeof body.backend !== "string") {
212
- json(res, { error: "backend is required" }, 400);
213
- return;
214
- }
215
- await runtime.switchBackend(body.backend);
216
- json(res, { ok: true });
217
- return;
408
+ }
409
+ json(res, { ok: true });
410
+ return true;
411
+ }
412
+ if (method === "POST" && path2 === "/provider/switch") {
413
+ const body = await readBody(req, maxBodySize);
414
+ if (!body.providerId || typeof body.providerId !== "string") {
415
+ json(res, { error: "providerId is required" }, 400);
416
+ return true;
417
+ }
418
+ if (!providerStore) {
419
+ json(res, { error: "No provider store configured" }, 400);
420
+ return true;
421
+ }
422
+ const provider = await providerStore.get(body.providerId);
423
+ if (!provider) {
424
+ json(res, { error: `Provider "${body.providerId}" not found` }, 404);
425
+ return true;
426
+ }
427
+ if (hooks?.onProviderSwitch) {
428
+ try {
429
+ await hooks.onProviderSwitch({ providerId: body.providerId, backend: provider.backend });
430
+ } catch (err) {
431
+ json(res, { error: err instanceof Error ? err.message : String(err) }, 400);
432
+ return true;
218
433
  }
219
- if (method === "POST" && path2 === "/model/switch") {
220
- const body = await readBody(req, maxBodySize);
221
- if (!body.model || typeof body.model !== "string") {
222
- json(res, { error: "model is required" }, 400);
223
- return;
224
- }
225
- runtime.switchModel(body.model);
226
- json(res, { ok: true });
227
- return;
434
+ }
435
+ json(res, { ok: true });
436
+ return true;
437
+ }
438
+ return false;
439
+ };
440
+ var providerRoutes = async (method, path2, req, res, ctx) => {
441
+ const { providerStore, maxBodySize } = ctx;
442
+ if (!providerStore) return false;
443
+ const idMatch = path2.match(/^\/providers\/([^/]+)$/);
444
+ if (method === "GET" && path2 === "/providers") {
445
+ const providers = await providerStore.list();
446
+ json(res, providers);
447
+ return true;
448
+ }
449
+ if (method === "GET" && idMatch) {
450
+ const id = decodeURIComponent(idMatch[1]);
451
+ const provider = await providerStore.get(id);
452
+ if (!provider) {
453
+ json(res, { error: "Provider not found" }, 404);
454
+ return true;
455
+ }
456
+ json(res, provider);
457
+ return true;
458
+ }
459
+ if (method === "POST" && path2 === "/providers") {
460
+ const body = await readBody(req, maxBodySize);
461
+ const backend = body.backend;
462
+ const model = body.model;
463
+ const label = body.label;
464
+ if (!backend || typeof backend !== "string") {
465
+ json(res, { error: "backend is required" }, 400);
466
+ return true;
467
+ }
468
+ if (!model || typeof model !== "string") {
469
+ json(res, { error: "model is required" }, 400);
470
+ return true;
471
+ }
472
+ if (!label || typeof label !== "string") {
473
+ json(res, { error: "label is required" }, 400);
474
+ return true;
475
+ }
476
+ const config = {
477
+ id: crypto$1.randomUUID(),
478
+ backend,
479
+ model,
480
+ label,
481
+ createdAt: Date.now()
482
+ };
483
+ await providerStore.create(config);
484
+ json(res, config, 201);
485
+ return true;
486
+ }
487
+ if (method === "PUT" && idMatch) {
488
+ const id = decodeURIComponent(idMatch[1]);
489
+ const existing = await providerStore.get(id);
490
+ if (!existing) {
491
+ json(res, { error: "Provider not found" }, 404);
492
+ return true;
493
+ }
494
+ const body = await readBody(req, maxBodySize);
495
+ const changes = {};
496
+ if (body.backend && typeof body.backend === "string") changes.backend = body.backend;
497
+ if (body.model && typeof body.model === "string") changes.model = body.model;
498
+ if (body.label && typeof body.label === "string") changes.label = body.label;
499
+ await providerStore.update(id, changes);
500
+ const updated = await providerStore.get(id);
501
+ json(res, updated);
502
+ return true;
503
+ }
504
+ if (method === "DELETE" && idMatch) {
505
+ const id = decodeURIComponent(idMatch[1]);
506
+ await providerStore.delete(id);
507
+ json(res, { ok: true });
508
+ return true;
509
+ }
510
+ return false;
511
+ };
512
+
513
+ // src/chat/server/handler.ts
514
+ var ROUTE_PIPELINE = [
515
+ sessionRoutes,
516
+ messageRoutes,
517
+ configRoutes,
518
+ providerRoutes
519
+ ];
520
+ function createChatHandler(runtime, options) {
521
+ const prefix = options?.prefix ?? "";
522
+ const state = {};
523
+ const ctx = {
524
+ runtime,
525
+ maxBodySize: options?.maxBodySize ?? 1048576,
526
+ heartbeatMs: options?.heartbeatMs,
527
+ hooks: options?.hooks,
528
+ providerStore: options?.providerStore,
529
+ tokenStore: options?.tokenStore,
530
+ transportFactory: options?.transportFactory,
531
+ state
532
+ };
533
+ return async (req, res) => {
534
+ const url = req.url || "";
535
+ const method = req.method || "GET";
536
+ const rawPath = prefix ? url.slice(prefix.length) : url;
537
+ const path2 = rawPath.split("?")[0];
538
+ try {
539
+ for (const route of ROUTE_PIPELINE) {
540
+ if (await route(method, path2, req, res, ctx)) return;
228
541
  }
229
542
  json(res, { error: "Not found" }, 404);
230
543
  } catch (err) {
@@ -232,55 +545,14 @@ function createChatHandler(runtime, options) {
232
545
  json(res, { error: err.message }, err.statusCode);
233
546
  } else {
234
547
  const message = err instanceof Error ? err.message : String(err);
548
+ if (ctx.hooks?.onError) {
549
+ ctx.hooks.onError(err instanceof Error ? err : new Error(message), { route: path2, method });
550
+ }
235
551
  json(res, { error: message }, 500);
236
552
  }
237
553
  }
238
554
  };
239
555
  }
240
- var BodyParseError = class extends Error {
241
- statusCode;
242
- constructor(message, statusCode) {
243
- super(message);
244
- this.name = "BodyParseError";
245
- this.statusCode = statusCode;
246
- }
247
- };
248
- function readBody(req, maxSize) {
249
- return new Promise((resolve2, reject) => {
250
- let body = "";
251
- let size = 0;
252
- let exceeded = false;
253
- req.on("data", (chunk) => {
254
- if (exceeded) return;
255
- const str = chunk.toString();
256
- size += Buffer.byteLength(str);
257
- if (size > maxSize) {
258
- exceeded = true;
259
- reject(new BodyParseError("Request body too large", 413));
260
- return;
261
- }
262
- body += str;
263
- });
264
- req.on("end", () => {
265
- if (exceeded) return;
266
- try {
267
- resolve2(JSON.parse(body || "{}"));
268
- } catch {
269
- reject(new BodyParseError("Invalid JSON in request body", 400));
270
- }
271
- });
272
- if ("once" in req && typeof req.once === "function") {
273
- req.once(
274
- "error",
275
- () => reject(new BodyParseError("Request error", 500))
276
- );
277
- }
278
- });
279
- }
280
- function json(res, data, status = 200) {
281
- res.writeHead(status, { "Content-Type": "application/json" });
282
- res.end(JSON.stringify(data));
283
- }
284
556
 
285
557
  // src/chat/server/auth-handler.ts
286
558
  function createAuthHandler(options) {
@@ -296,74 +568,74 @@ function createAuthHandler(options) {
296
568
  const path2 = rawPath.split("?")[0];
297
569
  try {
298
570
  if (method === "POST" && path2 === "/auth/start") {
299
- const body = await readBody2(req, maxBodySize);
571
+ const body = await readBody(req, maxBodySize);
300
572
  const provider = body.provider;
301
573
  if (!provider || !isValidProvider(provider)) {
302
- json2(res, { error: "provider is required (copilot, claude, vercel-ai)" }, 400);
574
+ json(res, { error: "provider is required (copilot, claude, vercel-ai)" }, 400);
303
575
  return;
304
576
  }
305
577
  pendingCopilot = null;
306
578
  pendingClaude = null;
307
579
  if (provider === "copilot") {
308
580
  if (!options.createCopilotAuth) {
309
- json2(res, { error: "Copilot auth not configured" }, 400);
581
+ json(res, { error: "Copilot auth not configured" }, 400);
310
582
  return;
311
583
  }
312
584
  const auth = options.createCopilotAuth();
313
585
  const flow = await auth.startDeviceFlow();
314
586
  pendingCopilot = { waitForToken: flow.waitForToken };
315
- json2(res, { userCode: flow.userCode, verificationUrl: flow.verificationUrl });
587
+ json(res, { userCode: flow.userCode, verificationUrl: flow.verificationUrl });
316
588
  return;
317
589
  }
318
590
  if (provider === "claude") {
319
591
  if (!options.createClaudeAuth) {
320
- json2(res, { error: "Claude auth not configured" }, 400);
592
+ json(res, { error: "Claude auth not configured" }, 400);
321
593
  return;
322
594
  }
323
595
  const auth = options.createClaudeAuth();
324
596
  const flow = auth.startOAuthFlow();
325
597
  pendingClaude = { completeAuth: flow.completeAuth };
326
- json2(res, { authorizeUrl: flow.authorizeUrl });
598
+ json(res, { authorizeUrl: flow.authorizeUrl });
327
599
  return;
328
600
  }
329
- json2(res, { ready: true });
601
+ json(res, { ready: true });
330
602
  return;
331
603
  }
332
604
  if (method === "POST" && path2 === "/auth/copilot/poll") {
333
605
  if (!pendingCopilot) {
334
- json2(res, { error: "No active Copilot flow" }, 400);
606
+ json(res, { error: "No active Copilot flow" }, 400);
335
607
  return;
336
608
  }
337
609
  const token = await pendingCopilot.waitForToken();
338
610
  pendingCopilot = null;
339
611
  await tokenStore.save("copilot", token);
340
612
  if (onAuth) await onAuth("copilot", token);
341
- json2(res, { ok: true, login: token.login });
613
+ json(res, { ok: true, login: token.login });
342
614
  return;
343
615
  }
344
616
  if (method === "POST" && path2 === "/auth/claude/complete") {
345
617
  if (!pendingClaude) {
346
- json2(res, { error: "No active Claude flow" }, 400);
618
+ json(res, { error: "No active Claude flow" }, 400);
347
619
  return;
348
620
  }
349
- const body = await readBody2(req, maxBodySize);
621
+ const body = await readBody(req, maxBodySize);
350
622
  const code = body.code;
351
623
  if (!code || typeof code !== "string") {
352
- json2(res, { error: "code is required" }, 400);
624
+ json(res, { error: "code is required" }, 400);
353
625
  return;
354
626
  }
355
627
  const token = await pendingClaude.completeAuth(code);
356
628
  pendingClaude = null;
357
629
  await tokenStore.save("claude", token);
358
630
  if (onAuth) await onAuth("claude", token);
359
- json2(res, { ok: true });
631
+ json(res, { ok: true });
360
632
  return;
361
633
  }
362
634
  if (method === "POST" && path2 === "/auth/vercel/complete") {
363
- const body = await readBody2(req, maxBodySize);
635
+ const body = await readBody(req, maxBodySize);
364
636
  const apiKey = body.apiKey;
365
637
  if (!apiKey || typeof apiKey !== "string") {
366
- json2(res, { error: "apiKey is required" }, 400);
638
+ json(res, { error: "apiKey is required" }, 400);
367
639
  return;
368
640
  }
369
641
  const token = {
@@ -374,86 +646,57 @@ function createAuthHandler(options) {
374
646
  const storeToken = body.baseUrl ? { ...token, baseUrl: body.baseUrl } : token;
375
647
  await tokenStore.save("vercel-ai", storeToken);
376
648
  if (onAuth) await onAuth("vercel-ai", storeToken);
377
- json2(res, { ok: true });
649
+ json(res, { ok: true });
378
650
  return;
379
651
  }
380
652
  if (method === "GET" && path2 === "/tokens/saved") {
381
653
  const saved = await tokenStore.list();
382
- json2(res, { saved });
654
+ json(res, { saved });
383
655
  return;
384
656
  }
385
657
  if (method === "POST" && path2 === "/tokens/use") {
386
- const body = await readBody2(req, maxBodySize);
658
+ const body = await readBody(req, maxBodySize);
387
659
  const provider = body.provider;
388
660
  if (!provider || !isValidProvider(provider)) {
389
- json2(res, { error: "provider is required (copilot, claude, vercel-ai)" }, 400);
661
+ json(res, { error: "provider is required (copilot, claude, vercel-ai)" }, 400);
390
662
  return;
391
663
  }
392
664
  const token = await tokenStore.load(provider);
393
665
  if (!token) {
394
- json2(res, { error: `No saved token for ${provider}` }, 404);
666
+ json(res, { error: `No saved token for ${provider}` }, 404);
395
667
  return;
396
668
  }
397
669
  if (onAuth) await onAuth(provider, token);
398
- json2(res, { ok: true, provider });
670
+ json(res, { ok: true, provider });
399
671
  return;
400
672
  }
401
673
  if (method === "POST" && path2 === "/tokens/clear") {
402
674
  await tokenStore.clearAll();
403
675
  if (options.onLogout) await options.onLogout();
404
- json2(res, { ok: true });
676
+ json(res, { ok: true });
405
677
  return;
406
678
  }
407
679
  if (method === "POST" && path2 === "/auth/dispose") {
408
680
  pendingCopilot = null;
409
681
  pendingClaude = null;
410
682
  if (options.onLogout) await options.onLogout();
411
- json2(res, { ok: true });
683
+ json(res, { ok: true });
412
684
  return;
413
685
  }
414
- json2(res, { error: "Not found" }, 404);
686
+ json(res, { error: "Not found" }, 404);
415
687
  } catch (err) {
416
- const message = err instanceof Error ? err.message : String(err);
417
- json2(res, { error: message }, 500);
688
+ if (err instanceof BodyParseError) {
689
+ json(res, { error: err.message }, err.statusCode);
690
+ } else {
691
+ const message = err instanceof Error ? err.message : String(err);
692
+ json(res, { error: message }, 500);
693
+ }
418
694
  }
419
695
  };
420
696
  }
421
697
  function isValidProvider(p) {
422
698
  return p === "copilot" || p === "claude" || p === "vercel-ai";
423
699
  }
424
- function readBody2(req, maxSize) {
425
- return new Promise((resolve2) => {
426
- let body = "";
427
- let size = 0;
428
- let exceeded = false;
429
- req.on("data", (chunk) => {
430
- if (exceeded) return;
431
- const str = chunk.toString();
432
- size += Buffer.byteLength(str);
433
- if (size > maxSize) {
434
- exceeded = true;
435
- resolve2({});
436
- return;
437
- }
438
- body += str;
439
- });
440
- req.on("end", () => {
441
- if (exceeded) return;
442
- try {
443
- resolve2(JSON.parse(body || "{}"));
444
- } catch {
445
- resolve2({});
446
- }
447
- });
448
- if ("once" in req && typeof req.once === "function") {
449
- req.once("error", () => resolve2({}));
450
- }
451
- });
452
- }
453
- function json2(res, data, status = 200) {
454
- res.writeHead(status, { "Content-Type": "application/json" });
455
- res.end(JSON.stringify(data));
456
- }
457
700
 
458
701
  // src/chat/server/cors.ts
459
702
  function corsMiddleware(options) {
@@ -484,6 +727,1208 @@ function corsMiddleware(options) {
484
727
  return false;
485
728
  };
486
729
  }
730
+
731
+ // src/chat/types.ts
732
+ function createChatId() {
733
+ return crypto.randomUUID();
734
+ }
735
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
736
+ function toChatId(value) {
737
+ if (!UUID_RE.test(value)) {
738
+ throw new TypeError(`Invalid ChatId: "${value}" is not a valid UUID`);
739
+ }
740
+ return value;
741
+ }
742
+
743
+ // src/chat/bridge.ts
744
+ function chatEventToAgentEvent(event) {
745
+ switch (event.type) {
746
+ case "message:delta":
747
+ return { type: "text_delta", text: event.text };
748
+ case "thinking:start":
749
+ return { type: "thinking_start" };
750
+ case "thinking:delta":
751
+ return { type: "thinking_delta", text: event.text };
752
+ case "thinking:end":
753
+ return { type: "thinking_end" };
754
+ case "tool:start":
755
+ return {
756
+ type: "tool_call_start",
757
+ toolCallId: event.toolCallId,
758
+ toolName: event.toolName,
759
+ args: event.args
760
+ };
761
+ case "tool:complete":
762
+ return {
763
+ type: "tool_call_end",
764
+ toolCallId: event.toolCallId,
765
+ toolName: event.toolName,
766
+ result: event.result
767
+ };
768
+ case "error":
769
+ return { type: "error", error: event.error, recoverable: event.recoverable, code: event.code };
770
+ default:
771
+ return null;
772
+ }
773
+ }
774
+
775
+ // src/chat/context.ts
776
+ function estimateTokens(message, options) {
777
+ const ratio = options?.charsPerToken ?? 4;
778
+ let charCount = 0;
779
+ charCount += message.role.length + 4;
780
+ for (const part of message.parts) {
781
+ charCount += estimatePartChars(part);
782
+ }
783
+ return Math.ceil(charCount / ratio);
784
+ }
785
+ function estimatePartChars(part) {
786
+ switch (part.type) {
787
+ case "text":
788
+ return part.text.length;
789
+ case "reasoning":
790
+ return part.text.length;
791
+ case "tool_call":
792
+ return JSON.stringify(part.args).length + part.name.length + 20 + (part.result !== void 0 ? JSON.stringify(part.result).length : 0);
793
+ case "source":
794
+ return (part.title?.length ?? 0) + part.url.length + 10;
795
+ case "file":
796
+ return part.name.length + part.data.length + 20;
797
+ }
798
+ }
799
+ var ContextWindowManager = class {
800
+ config;
801
+ constructor(config) {
802
+ this.config = {
803
+ maxTokens: config.maxTokens,
804
+ reservedTokens: config.reservedTokens ?? 0,
805
+ strategy: config.strategy ?? "truncate-oldest",
806
+ estimation: config.estimation,
807
+ summarizer: config.summarizer
808
+ };
809
+ }
810
+ /** Available token budget after reserving tokens */
811
+ get availableBudget() {
812
+ return Math.max(0, this.config.maxTokens - this.config.reservedTokens);
813
+ }
814
+ /**
815
+ * Estimate tokens for a single message.
816
+ * @param message - Message to estimate
817
+ * @returns Estimated token count
818
+ */
819
+ estimateMessageTokens(message) {
820
+ return estimateTokens(message, this.config.estimation);
821
+ }
822
+ /**
823
+ * Fit messages within the token budget using the configured strategy.
824
+ * @param messages - All messages to consider
825
+ * @returns Result with fitted messages and metadata
826
+ */
827
+ fitMessages(messages) {
828
+ if (messages.length === 0) {
829
+ return { messages: [], totalTokens: 0, removedCount: 0, wasTruncated: false };
830
+ }
831
+ const budget = this.availableBudget;
832
+ const tokenCounts = messages.map((m) => this.estimateMessageTokens(m));
833
+ const totalTokens = tokenCounts.reduce((a, b) => a + b, 0);
834
+ if (totalTokens <= budget) {
835
+ return {
836
+ messages: [...messages],
837
+ totalTokens,
838
+ removedCount: 0,
839
+ wasTruncated: false
840
+ };
841
+ }
842
+ switch (this.config.strategy) {
843
+ case "truncate-oldest":
844
+ return this.truncateOldest(messages, tokenCounts, budget);
845
+ case "sliding-window":
846
+ return this.slidingWindow(messages, tokenCounts, budget);
847
+ case "summarize-placeholder":
848
+ return this.summarizePlaceholder(messages, tokenCounts, budget);
849
+ }
850
+ }
851
+ /**
852
+ * Async variant of fitMessages that supports async summarization.
853
+ * When strategy is "summarize-placeholder" and a summarizer is configured,
854
+ * calls the summarizer with removed messages and replaces the placeholder text.
855
+ * Falls back to static placeholder if summarizer throws.
856
+ * For other strategies, behaves identically to fitMessages().
857
+ */
858
+ async fitMessagesAsync(messages) {
859
+ const result = this.fitMessages(messages);
860
+ if (this.config.strategy !== "summarize-placeholder" || !result.wasTruncated || !this.config.summarizer) {
861
+ return result;
862
+ }
863
+ const keptIds = new Set(result.messages.map((m) => m.id));
864
+ const removed = messages.filter((m) => !keptIds.has(m.id));
865
+ if (removed.length === 0) return result;
866
+ let summaryText;
867
+ try {
868
+ summaryText = await this.config.summarizer(removed);
869
+ } catch {
870
+ return result;
871
+ }
872
+ const updatedMessages = result.messages.map((m) => {
873
+ if (m.metadata?.isSummary === true) {
874
+ return {
875
+ ...m,
876
+ parts: [{ type: "text", text: summaryText, status: "complete" }]
877
+ };
878
+ }
879
+ return m;
880
+ });
881
+ return { ...result, messages: updatedMessages };
882
+ }
883
+ /**
884
+ * Trim messages using real token usage data from the previous API call.
885
+ * Uses average-based algorithm: `avgTokensPerMessage = lastPromptTokens / messageCount`.
886
+ * Removes oldest non-system messages until freed budget brings usage under modelContextWindow.
887
+ *
888
+ * @param messages - All messages in the session
889
+ * @param lastPromptTokens - Real prompt tokens from the last API response
890
+ * @param modelContextWindow - Model's total context window size in tokens
891
+ * @returns Result with fitted messages and metadata
892
+ */
893
+ fitMessagesWithUsage(messages, lastPromptTokens, modelContextWindow) {
894
+ if (messages.length === 0) {
895
+ return { messages: [], totalTokens: 0, removedCount: 0, wasTruncated: false };
896
+ }
897
+ const budget = modelContextWindow - this.config.reservedTokens;
898
+ if (budget <= 0 || lastPromptTokens <= budget) {
899
+ return {
900
+ messages: [...messages],
901
+ totalTokens: lastPromptTokens,
902
+ removedCount: 0,
903
+ wasTruncated: false
904
+ };
905
+ }
906
+ const avgTokensPerMessage = lastPromptTokens / messages.length;
907
+ const tokensToFree = lastPromptTokens - budget;
908
+ const messagesToRemove = Math.ceil(tokensToFree / avgTokensPerMessage);
909
+ const nonSystemIndices = [];
910
+ for (let i = 0; i < messages.length; i++) {
911
+ if (messages[i].role === "system") ; else {
912
+ nonSystemIndices.push(i);
913
+ }
914
+ }
915
+ const removableCount = Math.min(messagesToRemove, nonSystemIndices.length);
916
+ const removedIndices = new Set(nonSystemIndices.slice(0, removableCount));
917
+ const result = [];
918
+ for (let i = 0; i < messages.length; i++) {
919
+ if (!removedIndices.has(i)) {
920
+ result.push(messages[i]);
921
+ }
922
+ }
923
+ const estimatedTokens = Math.round(
924
+ lastPromptTokens * (result.length / messages.length)
925
+ );
926
+ return {
927
+ messages: result,
928
+ totalTokens: estimatedTokens,
929
+ removedCount: removableCount,
930
+ wasTruncated: removableCount > 0
931
+ };
932
+ }
933
+ /**
934
+ * Truncate oldest: keeps system messages, removes oldest non-system messages first.
935
+ * Always keeps the most recent user message.
936
+ */
937
+ truncateOldest(messages, tokenCounts, budget) {
938
+ const systemIndices = [];
939
+ const nonSystemIndices = [];
940
+ for (let i = 0; i < messages.length; i++) {
941
+ if (messages[i].role === "system") {
942
+ systemIndices.push(i);
943
+ } else {
944
+ nonSystemIndices.push(i);
945
+ }
946
+ }
947
+ let usedTokens = systemIndices.reduce(
948
+ (sum, i) => sum + tokenCounts[i],
949
+ 0
950
+ );
951
+ const includedNonSystem = [];
952
+ for (let i = nonSystemIndices.length - 1; i >= 0; i--) {
953
+ const idx = nonSystemIndices[i];
954
+ if (usedTokens + tokenCounts[idx] <= budget) {
955
+ includedNonSystem.unshift(idx);
956
+ usedTokens += tokenCounts[idx];
957
+ }
958
+ }
959
+ const includedSet = /* @__PURE__ */ new Set([...systemIndices, ...includedNonSystem]);
960
+ const result = [];
961
+ let resultTokens = 0;
962
+ for (let i = 0; i < messages.length; i++) {
963
+ if (includedSet.has(i)) {
964
+ result.push(messages[i]);
965
+ resultTokens += tokenCounts[i];
966
+ }
967
+ }
968
+ return {
969
+ messages: result,
970
+ totalTokens: resultTokens,
971
+ removedCount: messages.length - result.length,
972
+ wasTruncated: true
973
+ };
974
+ }
975
+ /**
976
+ * Sliding window: keeps the most recent messages that fit within budget.
977
+ */
978
+ slidingWindow(messages, tokenCounts, budget) {
979
+ const result = [];
980
+ let usedTokens = 0;
981
+ for (let i = messages.length - 1; i >= 0; i--) {
982
+ if (usedTokens + tokenCounts[i] <= budget) {
983
+ result.unshift(messages[i]);
984
+ usedTokens += tokenCounts[i];
985
+ } else {
986
+ break;
987
+ }
988
+ }
989
+ return {
990
+ messages: result,
991
+ totalTokens: usedTokens,
992
+ removedCount: messages.length - result.length,
993
+ wasTruncated: true
994
+ };
995
+ }
996
+ /**
997
+ * Summarize placeholder: replaces truncated messages with a placeholder,
998
+ * preserving system messages and recent context.
999
+ */
1000
+ summarizePlaceholder(messages, tokenCounts, budget) {
1001
+ const systemMessages = [];
1002
+ const nonSystem = [];
1003
+ for (let i = 0; i < messages.length; i++) {
1004
+ if (messages[i].role === "system") {
1005
+ systemMessages.push({ msg: messages[i], tokens: tokenCounts[i] });
1006
+ } else {
1007
+ nonSystem.push({ msg: messages[i], tokens: tokenCounts[i], idx: i });
1008
+ }
1009
+ }
1010
+ let usedTokens = systemMessages.reduce((s, m) => s + m.tokens, 0);
1011
+ const placeholderTokens = 20;
1012
+ usedTokens += placeholderTokens;
1013
+ const recentKept = [];
1014
+ for (let i = nonSystem.length - 1; i >= 0; i--) {
1015
+ if (usedTokens + nonSystem[i].tokens <= budget) {
1016
+ recentKept.unshift(nonSystem[i]);
1017
+ usedTokens += nonSystem[i].tokens;
1018
+ } else {
1019
+ break;
1020
+ }
1021
+ }
1022
+ const removedCount = messages.length - systemMessages.length - recentKept.length;
1023
+ const result = [];
1024
+ for (const sm of systemMessages) {
1025
+ result.push(sm.msg);
1026
+ }
1027
+ if (removedCount > 0) {
1028
+ result.push({
1029
+ id: "context-placeholder",
1030
+ role: "system",
1031
+ parts: [{ type: "text", text: `[${removedCount} earlier message${removedCount === 1 ? "" : "s"} omitted for context window]`, status: "complete" }],
1032
+ metadata: { isSummary: true },
1033
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1034
+ status: "complete"
1035
+ });
1036
+ }
1037
+ for (const m of recentKept) {
1038
+ result.push(m.msg);
1039
+ }
1040
+ return {
1041
+ messages: result,
1042
+ totalTokens: usedTokens,
1043
+ removedCount,
1044
+ wasTruncated: true
1045
+ };
1046
+ }
1047
+ };
1048
+
1049
+ // src/chat/state.ts
1050
+ var StateMachine = class {
1051
+ constructor(initial, transitions) {
1052
+ this.initial = initial;
1053
+ this.transitions = transitions;
1054
+ this._current = initial;
1055
+ }
1056
+ _current;
1057
+ /** Current state */
1058
+ get current() {
1059
+ return this._current;
1060
+ }
1061
+ /**
1062
+ * Check whether transitioning to `next` is allowed from current state
1063
+ * @param next - Target state to check
1064
+ * @returns True if transition is allowed
1065
+ */
1066
+ canTransition(next) {
1067
+ const allowed = this.transitions[this._current];
1068
+ return allowed !== void 0 && allowed.includes(next);
1069
+ }
1070
+ /**
1071
+ * Transition to `next` state.
1072
+ * @throws ChatError(INVALID_TRANSITION) if the transition is not allowed
1073
+ */
1074
+ transition(next) {
1075
+ if (!this.canTransition(next)) {
1076
+ throw new ChatError(
1077
+ `Invalid transition: ${this._current} \u2192 ${next}`,
1078
+ { code: "INVALID_TRANSITION" /* INVALID_TRANSITION */ }
1079
+ );
1080
+ }
1081
+ this._current = next;
1082
+ }
1083
+ /** Reset to initial state */
1084
+ reset() {
1085
+ this._current = this.initial;
1086
+ }
1087
+ };
1088
+ var RUNTIME_TRANSITIONS = {
1089
+ idle: ["streaming", "disposed"],
1090
+ streaming: ["idle", "error", "disposed"],
1091
+ error: ["idle", "disposed"],
1092
+ disposed: []
1093
+ };
1094
+ var ChatReentrancyGuard = class {
1095
+ _acquired = false;
1096
+ /** Whether the guard is currently held */
1097
+ get isAcquired() {
1098
+ return this._acquired;
1099
+ }
1100
+ /**
1101
+ * Acquire the guard. Throws if already acquired.
1102
+ * @throws ChatError with code REENTRANCY
1103
+ */
1104
+ acquire() {
1105
+ if (this._acquired) {
1106
+ throw new ChatError(
1107
+ "Concurrent operation detected: a send is already in progress",
1108
+ { code: "REENTRANCY" /* REENTRANCY */ }
1109
+ );
1110
+ }
1111
+ this._acquired = true;
1112
+ }
1113
+ /** Release the guard. Safe to call even if not acquired. */
1114
+ release() {
1115
+ this._acquired = false;
1116
+ }
1117
+ };
1118
+ var ChatAbortController = class {
1119
+ _controller;
1120
+ _onExternalAbort;
1121
+ _externalSignal;
1122
+ constructor(externalSignal) {
1123
+ this._controller = new AbortController();
1124
+ this._externalSignal = externalSignal;
1125
+ if (externalSignal) {
1126
+ if (externalSignal.aborted) {
1127
+ this._controller.abort(externalSignal.reason);
1128
+ } else {
1129
+ this._onExternalAbort = () => {
1130
+ this._controller.abort(externalSignal.reason);
1131
+ };
1132
+ externalSignal.addEventListener("abort", this._onExternalAbort, { once: true });
1133
+ }
1134
+ }
1135
+ }
1136
+ /** The AbortSignal for this controller */
1137
+ get signal() {
1138
+ return this._controller.signal;
1139
+ }
1140
+ /** Whether the operation has been aborted */
1141
+ get isAborted() {
1142
+ return this._controller.signal.aborted;
1143
+ }
1144
+ /**
1145
+ * Abort the operation.
1146
+ * @param reason - Optional abort reason
1147
+ */
1148
+ abort(reason) {
1149
+ this._controller.abort(reason);
1150
+ }
1151
+ /** Clean up external signal listener to prevent memory leaks */
1152
+ dispose() {
1153
+ if (this._onExternalAbort && this._externalSignal) {
1154
+ this._externalSignal.removeEventListener("abort", this._onExternalAbort);
1155
+ }
1156
+ }
1157
+ };
1158
+
1159
+ // src/chat/accumulator.ts
1160
+ var MessageAccumulator = class {
1161
+ messageId;
1162
+ parts = [];
1163
+ status = "pending";
1164
+ currentTextPart = null;
1165
+ currentReasoningPart = null;
1166
+ toolCallParts = /* @__PURE__ */ new Map();
1167
+ _finalized = false;
1168
+ constructor(messageId) {
1169
+ this.messageId = messageId ?? createChatId();
1170
+ }
1171
+ /** Get current message ID */
1172
+ get id() {
1173
+ return this.messageId;
1174
+ }
1175
+ /**
1176
+ * Apply an AgentEvent to accumulate into the message
1177
+ * @param event - AgentEvent to process
1178
+ * @throws Error if accumulator is already finalized
1179
+ */
1180
+ apply(event) {
1181
+ if (this._finalized) throw new Error("Cannot apply events to finalized accumulator");
1182
+ if (this.status === "pending") {
1183
+ this.status = "streaming";
1184
+ }
1185
+ switch (event.type) {
1186
+ case "text_delta":
1187
+ this.handleTextDelta(event.text);
1188
+ break;
1189
+ case "thinking_start":
1190
+ this.finalizeCurrentText();
1191
+ this.currentReasoningPart = { type: "reasoning", text: "", status: "streaming" };
1192
+ this.parts.push(this.currentReasoningPart);
1193
+ break;
1194
+ case "thinking_delta":
1195
+ if (this.currentReasoningPart) {
1196
+ this.currentReasoningPart.text += event.text;
1197
+ }
1198
+ break;
1199
+ case "thinking_end":
1200
+ if (this.currentReasoningPart) {
1201
+ this.currentReasoningPart.status = "complete";
1202
+ this.currentReasoningPart = null;
1203
+ }
1204
+ break;
1205
+ case "tool_call_start": {
1206
+ this.finalizeCurrentText();
1207
+ const toolPart = {
1208
+ type: "tool_call",
1209
+ toolCallId: event.toolCallId,
1210
+ name: event.toolName,
1211
+ args: event.args,
1212
+ status: "running"
1213
+ };
1214
+ this.toolCallParts.set(event.toolCallId, toolPart);
1215
+ this.parts.push(toolPart);
1216
+ break;
1217
+ }
1218
+ case "tool_call_end": {
1219
+ const existing = this.toolCallParts.get(event.toolCallId);
1220
+ if (existing) {
1221
+ existing.result = event.result;
1222
+ existing.status = "complete";
1223
+ }
1224
+ break;
1225
+ }
1226
+ case "error":
1227
+ this.status = "error";
1228
+ break;
1229
+ }
1230
+ }
1231
+ handleTextDelta(text) {
1232
+ if (!this.currentTextPart) {
1233
+ this.currentTextPart = { type: "text", text: "", status: "streaming" };
1234
+ this.parts.push(this.currentTextPart);
1235
+ }
1236
+ this.currentTextPart.text += text;
1237
+ }
1238
+ finalizeCurrentText() {
1239
+ if (this.currentTextPart) {
1240
+ this.currentTextPart.status = "complete";
1241
+ this.currentTextPart = null;
1242
+ }
1243
+ }
1244
+ /**
1245
+ * Get a snapshot of the current accumulated message (for streaming UI)
1246
+ * @returns ChatMessage with current parts and "streaming" status
1247
+ */
1248
+ snapshot() {
1249
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1250
+ return {
1251
+ id: this.messageId,
1252
+ role: "assistant",
1253
+ parts: this.parts.map((p) => ({ ...p })),
1254
+ status: this.status === "pending" ? "pending" : "streaming",
1255
+ createdAt: now,
1256
+ updatedAt: now
1257
+ };
1258
+ }
1259
+ /**
1260
+ * Finalize the accumulator and return the complete ChatMessage
1261
+ * @returns Completed ChatMessage with all parts finalized
1262
+ * @throws Error if accumulator is already finalized
1263
+ */
1264
+ finalize() {
1265
+ if (this._finalized) throw new Error("Accumulator already finalized");
1266
+ this._finalized = true;
1267
+ this.finalizeCurrentText();
1268
+ if (this.currentReasoningPart) {
1269
+ this.currentReasoningPart.status = "complete";
1270
+ this.currentReasoningPart = null;
1271
+ }
1272
+ for (const [, toolPart] of this.toolCallParts) {
1273
+ if (toolPart.status === "running" || toolPart.status === "pending") {
1274
+ toolPart.status = "error";
1275
+ }
1276
+ }
1277
+ if (this.status !== "error" && this.status !== "cancelled") {
1278
+ this.status = "complete";
1279
+ }
1280
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1281
+ return {
1282
+ id: this.messageId,
1283
+ role: "assistant",
1284
+ parts: this.parts,
1285
+ status: this.status,
1286
+ createdAt: now,
1287
+ updatedAt: now
1288
+ };
1289
+ }
1290
+ /** Check if the accumulator has been finalized */
1291
+ get finalized() {
1292
+ return this._finalized;
1293
+ }
1294
+ };
1295
+
1296
+ // src/chat/watchdog.ts
1297
+ async function* withStreamWatchdog(source, config) {
1298
+ const { timeoutMs, signal } = config;
1299
+ const iterator = source[Symbol.asyncIterator]();
1300
+ let aborted = false;
1301
+ if (signal?.aborted) {
1302
+ iterator.return?.();
1303
+ return;
1304
+ }
1305
+ const onAbort = () => {
1306
+ aborted = true;
1307
+ iterator.return?.();
1308
+ };
1309
+ signal?.addEventListener("abort", onAbort, { once: true });
1310
+ try {
1311
+ while (true) {
1312
+ if (aborted) break;
1313
+ const timeout = new CancellableTimeout(timeoutMs);
1314
+ try {
1315
+ const result = await Promise.race([
1316
+ iterator.next(),
1317
+ timeout.promise
1318
+ ]);
1319
+ timeout.cancel();
1320
+ if (result.done) break;
1321
+ yield result.value;
1322
+ } catch (err) {
1323
+ timeout.cancel();
1324
+ throw err;
1325
+ }
1326
+ }
1327
+ } finally {
1328
+ signal?.removeEventListener("abort", onAbort);
1329
+ iterator.return?.();
1330
+ }
1331
+ }
1332
+ var CancellableTimeout = class {
1333
+ promise;
1334
+ _timer;
1335
+ _cancelled = false;
1336
+ constructor(ms) {
1337
+ this.promise = new Promise((_, reject) => {
1338
+ this._timer = setTimeout(() => {
1339
+ if (!this._cancelled) {
1340
+ reject(
1341
+ new ChatError(
1342
+ `Stream timed out after ${ms}ms of inactivity`,
1343
+ { code: "TIMEOUT" /* TIMEOUT */ }
1344
+ )
1345
+ );
1346
+ }
1347
+ }, ms);
1348
+ });
1349
+ this.promise.catch(() => {
1350
+ });
1351
+ }
1352
+ cancel() {
1353
+ this._cancelled = true;
1354
+ if (this._timer !== void 0) {
1355
+ clearTimeout(this._timer);
1356
+ this._timer = void 0;
1357
+ }
1358
+ }
1359
+ };
1360
+
1361
+ // src/chat/listener-set.ts
1362
+ var ListenerSet = class {
1363
+ _listeners = /* @__PURE__ */ new Set();
1364
+ /** Add a listener. Returns an unsubscribe function. */
1365
+ add(callback) {
1366
+ this._listeners.add(callback);
1367
+ return () => {
1368
+ this._listeners.delete(callback);
1369
+ };
1370
+ }
1371
+ /** Notify all listeners with the given arguments. Errors are isolated per listener. */
1372
+ notify(...args) {
1373
+ for (const cb of this._listeners) {
1374
+ try {
1375
+ cb(...args);
1376
+ } catch {
1377
+ }
1378
+ }
1379
+ }
1380
+ /** Remove all listeners. */
1381
+ clear() {
1382
+ this._listeners.clear();
1383
+ }
1384
+ /** Current number of listeners. */
1385
+ get size() {
1386
+ return this._listeners.size;
1387
+ }
1388
+ };
1389
+
1390
+ // src/chat/runtime.ts
1391
+ var ChatRuntime = class {
1392
+ _state;
1393
+ _guard;
1394
+ _backends;
1395
+ _sessionStore;
1396
+ _contextConfig;
1397
+ _middleware;
1398
+ _tools = /* @__PURE__ */ new Map();
1399
+ _retryConfig;
1400
+ _contextStats = /* @__PURE__ */ new Map();
1401
+ _sessionUsage = /* @__PURE__ */ new Map();
1402
+ _modelContextWindows = /* @__PURE__ */ new Map();
1403
+ _onContextTrimmed;
1404
+ _streamTimeoutMs;
1405
+ _sessionListeners = new ListenerSet();
1406
+ _adapterPool = /* @__PURE__ */ new Map();
1407
+ _defaultBackend;
1408
+ _abortController = null;
1409
+ constructor(options) {
1410
+ this._state = new StateMachine("idle", RUNTIME_TRANSITIONS);
1411
+ this._guard = new ChatReentrancyGuard();
1412
+ this._backends = options.backends;
1413
+ this._defaultBackend = options.defaultBackend;
1414
+ this._sessionStore = options.sessionStore;
1415
+ this._contextConfig = options.context;
1416
+ this._middleware = [...options.middleware ?? []];
1417
+ this._retryConfig = options.retryConfig;
1418
+ this._onContextTrimmed = options.onContextTrimmed;
1419
+ this._streamTimeoutMs = options.streamTimeoutMs;
1420
+ if (!options.backends[options.defaultBackend]) {
1421
+ throw new ChatError(
1422
+ `Default backend "${options.defaultBackend}" not found in backends map`,
1423
+ { code: "INVALID_INPUT" /* INVALID_INPUT */ }
1424
+ );
1425
+ }
1426
+ if (options.tools) {
1427
+ for (const tool of options.tools) {
1428
+ this._tools.set(tool.name, tool);
1429
+ }
1430
+ }
1431
+ }
1432
+ // ── Lifecycle ──────────────────────────────────────────────
1433
+ get status() {
1434
+ return this._state.current;
1435
+ }
1436
+ async dispose() {
1437
+ if (this._state.current === "disposed") return;
1438
+ this._abortController?.abort("Runtime disposed");
1439
+ this._abortController?.dispose();
1440
+ this._abortController = null;
1441
+ this._state.transition("disposed");
1442
+ for (const adapter of this._adapterPool.values()) {
1443
+ try {
1444
+ await adapter.dispose();
1445
+ } catch {
1446
+ }
1447
+ }
1448
+ this._adapterPool.clear();
1449
+ }
1450
+ // ── Sessions ───────────────────────────────────────────────
1451
+ async createSession(options) {
1452
+ this.assertNotDisposed();
1453
+ const config = {
1454
+ model: options.config?.model ?? "",
1455
+ backend: options.config?.backend ?? this._defaultBackend,
1456
+ ...options.config
1457
+ };
1458
+ const session = await this._sessionStore.createSession({ ...options, config });
1459
+ this._notifySessionChange();
1460
+ return session;
1461
+ }
1462
+ async getSession(id) {
1463
+ this.assertNotDisposed();
1464
+ const cid = toChatId(id);
1465
+ return this._sessionStore.getSession(cid);
1466
+ }
1467
+ async listSessions(options) {
1468
+ this.assertNotDisposed();
1469
+ return this._sessionStore.listSessions(options);
1470
+ }
1471
+ async deleteSession(id) {
1472
+ this.assertNotDisposed();
1473
+ const cid = toChatId(id);
1474
+ const session = await this._sessionStore.getSession(cid);
1475
+ if (!session) return;
1476
+ await this._sessionStore.deleteSession(cid);
1477
+ this._contextStats.delete(cid);
1478
+ this._sessionUsage.delete(cid);
1479
+ this._notifySessionChange();
1480
+ }
1481
+ // ── Messaging ──────────────────────────────────────────────
1482
+ async *send(sessionId, message, options) {
1483
+ this.validateSendInput(message, options);
1484
+ this._guard.acquire();
1485
+ const cid = toChatId(sessionId);
1486
+ this._abortController = new ChatAbortController(options?.signal);
1487
+ try {
1488
+ if (this._state.current === "error") {
1489
+ this._state.transition("idle");
1490
+ }
1491
+ this._state.transition("streaming");
1492
+ await this.loadSession(cid);
1493
+ const mwCtx = {
1494
+ sessionId: cid,
1495
+ signal: this._abortController.signal
1496
+ };
1497
+ const userMessage = await this.applyBeforeSendMiddleware(
1498
+ this.createUserMessage(message),
1499
+ mwCtx
1500
+ );
1501
+ if (userMessage === null) {
1502
+ this._state.transition("idle");
1503
+ return;
1504
+ }
1505
+ const updatedSession = await this.persistAndReload(cid, userMessage);
1506
+ const sessionForAdapter = await this.trimSessionContext(cid, updatedSession, options.model);
1507
+ const stream = await this.prepareEventStream(
1508
+ cid,
1509
+ sessionForAdapter,
1510
+ updatedSession,
1511
+ message,
1512
+ options
1513
+ );
1514
+ const accumulator = new MessageAccumulator();
1515
+ const eventSource = this._streamTimeoutMs ? withStreamWatchdog(stream, { timeoutMs: this._streamTimeoutMs, signal: this._abortController.signal }) : stream;
1516
+ for await (const event of eventSource) {
1517
+ if (this._abortController.isAborted) break;
1518
+ this.feedAccumulator(accumulator, event);
1519
+ if (event.type === "usage") {
1520
+ this._sessionUsage.set(cid, {
1521
+ promptTokens: event.promptTokens,
1522
+ completionTokens: event.completionTokens
1523
+ });
1524
+ this.updateContextStatsWithUsage(cid, event.promptTokens, event.completionTokens, options);
1525
+ }
1526
+ const processed = await this.applyOnEventMiddleware(event, mwCtx);
1527
+ if (processed) yield processed;
1528
+ }
1529
+ if (this._state.current === "disposed") return;
1530
+ await this.finalizeAssistantMessage(cid, accumulator, mwCtx);
1531
+ this._state.transition("idle");
1532
+ } catch (error) {
1533
+ const result = await this.handleSendError(error, cid);
1534
+ if (result !== null) throw result;
1535
+ } finally {
1536
+ this._guard.release();
1537
+ this._abortController?.dispose();
1538
+ this._abortController = null;
1539
+ }
1540
+ }
1541
+ // ── Send Pipeline Stages ──────────────────────────────────────
1542
+ /** Stage 1: Validate send inputs (message content + required fields). */
1543
+ validateSendInput(message, options) {
1544
+ this.assertNotDisposed();
1545
+ if (!message || message.trim().length === 0) {
1546
+ throw new ChatError("Message cannot be empty", { code: "INVALID_INPUT" /* INVALID_INPUT */ });
1547
+ }
1548
+ if (!options.model) {
1549
+ throw new ChatError(
1550
+ "options.model is required \u2014 caller must specify which model to use",
1551
+ { code: "INVALID_INPUT" /* INVALID_INPUT */ }
1552
+ );
1553
+ }
1554
+ if (!options.backend) {
1555
+ throw new ChatError(
1556
+ "options.backend is required \u2014 caller must specify which backend to use",
1557
+ { code: "INVALID_INPUT" /* INVALID_INPUT */ }
1558
+ );
1559
+ }
1560
+ if (!options.credentials) {
1561
+ throw new ChatError(
1562
+ "options.credentials is required \u2014 caller must provide authentication credentials",
1563
+ { code: "INVALID_INPUT" /* INVALID_INPUT */ }
1564
+ );
1565
+ }
1566
+ }
1567
+ /** Stage 2: Load session from store. */
1568
+ async loadSession(cid) {
1569
+ const session = await this._sessionStore.getSession(cid);
1570
+ if (!session) {
1571
+ throw new ChatError(
1572
+ `Session "${cid}" not found`,
1573
+ { code: "SESSION_NOT_FOUND" /* SESSION_NOT_FOUND */ }
1574
+ );
1575
+ }
1576
+ return session;
1577
+ }
1578
+ /** Stage 3: Apply onBeforeSend middleware pipeline. Returns null if middleware rejected the send. */
1579
+ async applyBeforeSendMiddleware(userMessage, ctx) {
1580
+ let msg = userMessage;
1581
+ for (const mw of this._middleware) {
1582
+ if (mw.onBeforeSend && msg) {
1583
+ msg = await mw.onBeforeSend(msg, ctx);
1584
+ if (msg === null) return null;
1585
+ }
1586
+ }
1587
+ return msg;
1588
+ }
1589
+ /** Stage 4: Persist user message and reload session with full history. */
1590
+ async persistAndReload(cid, userMessage) {
1591
+ await this._sessionStore.appendMessage(cid, userMessage);
1592
+ return await this._sessionStore.getSession(cid);
1593
+ }
1594
+ /** Stage 5: Auto-trim context window if configured. Returns session snapshot for adapter. */
1595
+ async trimSessionContext(cid, session, model) {
1596
+ if (!this._contextConfig) return session;
1597
+ const ctxManager = new ContextWindowManager(this._contextConfig);
1598
+ const lastUsage = this._sessionUsage.get(cid);
1599
+ const modelContextWindow = model ? this._modelContextWindows.get(model) : void 0;
1600
+ if (lastUsage && modelContextWindow) {
1601
+ const result2 = ctxManager.fitMessagesWithUsage(
1602
+ session.messages,
1603
+ lastUsage.promptTokens,
1604
+ modelContextWindow
1605
+ );
1606
+ this._contextStats.set(cid, {
1607
+ totalTokens: result2.totalTokens,
1608
+ removedCount: result2.removedCount,
1609
+ wasTruncated: result2.wasTruncated,
1610
+ availableBudget: Math.max(0, modelContextWindow - result2.totalTokens),
1611
+ realPromptTokens: lastUsage.promptTokens,
1612
+ realCompletionTokens: lastUsage.completionTokens,
1613
+ modelContextWindow
1614
+ });
1615
+ if (result2.wasTruncated && this._onContextTrimmed) {
1616
+ const keptIds = new Set(result2.messages.map((m) => m.id));
1617
+ const removed = session.messages.filter((m) => !keptIds.has(m.id));
1618
+ if (removed.length > 0) {
1619
+ try {
1620
+ this._onContextTrimmed(cid, removed);
1621
+ } catch {
1622
+ }
1623
+ }
1624
+ }
1625
+ return { ...session, messages: result2.messages };
1626
+ }
1627
+ const result = await ctxManager.fitMessagesAsync(session.messages);
1628
+ this._contextStats.set(cid, {
1629
+ totalTokens: result.totalTokens,
1630
+ removedCount: result.removedCount,
1631
+ wasTruncated: result.wasTruncated,
1632
+ availableBudget: ctxManager.availableBudget,
1633
+ modelContextWindow
1634
+ });
1635
+ if (result.wasTruncated && this._onContextTrimmed) {
1636
+ const keptIds = new Set(result.messages.map((m) => m.id));
1637
+ const removed = session.messages.filter((m) => !keptIds.has(m.id));
1638
+ if (removed.length > 0) {
1639
+ try {
1640
+ this._onContextTrimmed(cid, removed);
1641
+ } catch {
1642
+ }
1643
+ }
1644
+ }
1645
+ return { ...session, messages: result.messages };
1646
+ }
1647
+ /** Update context stats with real usage data from a usage event. */
1648
+ updateContextStatsWithUsage(cid, promptTokens, completionTokens, options) {
1649
+ const modelContextWindow = options.model ? this._modelContextWindows.get(options.model) : void 0;
1650
+ const existing = this._contextStats.get(cid);
1651
+ this._contextStats.set(cid, {
1652
+ totalTokens: promptTokens,
1653
+ removedCount: existing?.removedCount ?? 0,
1654
+ wasTruncated: existing?.wasTruncated ?? false,
1655
+ availableBudget: modelContextWindow ? Math.max(0, modelContextWindow - promptTokens) : existing?.availableBudget ?? 0,
1656
+ realPromptTokens: promptTokens,
1657
+ realCompletionTokens: completionTokens,
1658
+ modelContextWindow
1659
+ });
1660
+ }
1661
+ /** Stage 6: Prepare event stream — adapter with retry, tool injection. */
1662
+ async prepareEventStream(cid, sessionForAdapter, fullSession, message, options) {
1663
+ const adapter = await this.getOrCreateAdapterWithRetry(options.backend, options.credentials);
1664
+ const runtimeTools = this._tools.size > 0 ? this.injectToolContext([...this._tools.values()], {
1665
+ sessionId: cid,
1666
+ custom: fullSession.metadata?.custom
1667
+ }) : void 0;
1668
+ const streamOptions = {
1669
+ signal: this._abortController.signal,
1670
+ model: options.model,
1671
+ systemPrompt: options.systemPrompt,
1672
+ tools: runtimeTools
1673
+ };
1674
+ return this.createStreamWithRetry(
1675
+ adapter,
1676
+ sessionForAdapter,
1677
+ message,
1678
+ streamOptions,
1679
+ options.backend,
1680
+ options.credentials
1681
+ );
1682
+ }
1683
+ /** Stage 7: Apply onEvent middleware pipeline (sequential transform/suppress). */
1684
+ async applyOnEventMiddleware(event, ctx) {
1685
+ let processed = event;
1686
+ for (const mw of this._middleware) {
1687
+ if (mw.onEvent && processed) {
1688
+ processed = await mw.onEvent(processed, ctx);
1689
+ }
1690
+ }
1691
+ return processed;
1692
+ }
1693
+ /** Stage 8: Finalize accumulator, apply afterReceive middleware, persist assistant message. */
1694
+ async finalizeAssistantMessage(cid, accumulator, ctx) {
1695
+ let assistantMessage = accumulator.finalize();
1696
+ for (const mw of this._middleware) {
1697
+ if (mw.onAfterReceive) {
1698
+ assistantMessage = await mw.onAfterReceive(assistantMessage, ctx);
1699
+ }
1700
+ }
1701
+ await this._sessionStore.appendMessage(cid, assistantMessage);
1702
+ this._notifySessionChange();
1703
+ }
1704
+ /** Stage 9: Error handling — apply onError middleware, transition state. Returns null if suppressed. */
1705
+ async handleSendError(error, cid) {
1706
+ let processedError = error instanceof Error ? error : new Error(String(error));
1707
+ const ctx = {
1708
+ sessionId: cid,
1709
+ signal: this._abortController?.signal ?? new AbortController().signal
1710
+ };
1711
+ for (const mw of this._middleware) {
1712
+ if (mw.onError) {
1713
+ const result = await mw.onError(processedError, ctx);
1714
+ if (result === null) {
1715
+ if (this._state.canTransition("idle")) {
1716
+ this._state.transition("idle");
1717
+ }
1718
+ return null;
1719
+ }
1720
+ processedError = result;
1721
+ }
1722
+ }
1723
+ if (this._state.canTransition("error")) {
1724
+ this._state.transition("error");
1725
+ }
1726
+ return processedError;
1727
+ }
1728
+ abort() {
1729
+ this._abortController?.abort("User abort");
1730
+ }
1731
+ // ── Backend / Model ────────────────────────────────────────
1732
+ async listModels(options) {
1733
+ this.assertNotDisposed();
1734
+ let models = [];
1735
+ const firstAdapter = [...this._adapterPool.values()][0];
1736
+ if (firstAdapter) {
1737
+ try {
1738
+ models = await firstAdapter.listModels();
1739
+ } catch {
1740
+ return [];
1741
+ }
1742
+ } else if (options?.backend && options?.credentials) {
1743
+ try {
1744
+ const adapter = await this.getOrCreateAdapter(options.backend, options.credentials);
1745
+ models = await adapter.listModels();
1746
+ } catch {
1747
+ return [];
1748
+ }
1749
+ }
1750
+ for (const model of models) {
1751
+ if (model.contextWindow != null) {
1752
+ this._modelContextWindows.set(model.id, model.contextWindow);
1753
+ }
1754
+ }
1755
+ return models;
1756
+ }
1757
+ async listBackends() {
1758
+ this.assertNotDisposed();
1759
+ return Object.keys(this._backends).map((name) => ({ name }));
1760
+ }
1761
+ // ── Tools ──────────────────────────────────────────────────
1762
+ get registeredTools() {
1763
+ return this._tools;
1764
+ }
1765
+ registerTool(tool) {
1766
+ this.assertNotDisposed();
1767
+ this._tools.set(tool.name, tool);
1768
+ }
1769
+ removeTool(name) {
1770
+ this.assertNotDisposed();
1771
+ this._tools.delete(name);
1772
+ }
1773
+ // ── Middleware ──────────────────────────────────────────────
1774
+ use(middleware) {
1775
+ this.assertNotDisposed();
1776
+ this._middleware.push(middleware);
1777
+ }
1778
+ removeMiddleware(middleware) {
1779
+ this.assertNotDisposed();
1780
+ const idx = this._middleware.indexOf(middleware);
1781
+ if (idx >= 0) this._middleware.splice(idx, 1);
1782
+ }
1783
+ // ── Context Stats ─────────────────────────────────────────
1784
+ async getContextStats(sessionId) {
1785
+ const cid = toChatId(sessionId);
1786
+ return this._contextStats.get(cid) ?? null;
1787
+ }
1788
+ // ── Session Subscription ──────────────────────────────────
1789
+ onSessionChange(callback) {
1790
+ return this._sessionListeners.add(callback);
1791
+ }
1792
+ _notifySessionChange() {
1793
+ this._sessionListeners.notify();
1794
+ }
1795
+ // ── Private Helpers ────────────────────────────────────────
1796
+ async getOrCreateAdapter(backend, credentials) {
1797
+ const key = this.getPoolKey(backend, credentials);
1798
+ const existing = this._adapterPool.get(key);
1799
+ if (existing) return existing;
1800
+ for (const [oldKey, oldAdapter] of this._adapterPool) {
1801
+ if (oldKey.startsWith(backend + ":")) {
1802
+ try {
1803
+ await oldAdapter.dispose();
1804
+ } catch {
1805
+ }
1806
+ this._adapterPool.delete(oldKey);
1807
+ }
1808
+ }
1809
+ const factory = this._backends[backend];
1810
+ if (!factory) {
1811
+ throw new ChatError(
1812
+ `Backend "${backend}" not found`,
1813
+ { code: "INVALID_INPUT" /* INVALID_INPUT */ }
1814
+ );
1815
+ }
1816
+ const adapter = await factory(credentials);
1817
+ this._adapterPool.set(key, adapter);
1818
+ return adapter;
1819
+ }
1820
+ getPoolKey(backend, credentials) {
1821
+ const token = credentials.accessToken;
1822
+ const hash = token.length > 16 ? token.slice(0, 8) + token.slice(-8) : token;
1823
+ return `${backend}:${hash}`;
1824
+ }
1825
+ /** Wrap each tool's execute to inject ToolContext as 2nd argument */
1826
+ injectToolContext(tools, context) {
1827
+ return tools.map((tool) => ({
1828
+ ...tool,
1829
+ execute: (params) => tool.execute(params, context)
1830
+ }));
1831
+ }
1832
+ /** Map ChatEvent to AgentEvent for MessageAccumulator */
1833
+ feedAccumulator(acc, event) {
1834
+ const agentEvent = chatEventToAgentEvent(event);
1835
+ if (agentEvent) acc.apply(agentEvent);
1836
+ }
1837
+ createUserMessage(text) {
1838
+ return {
1839
+ id: createChatId(),
1840
+ role: "user",
1841
+ parts: [{ type: "text", text, status: "complete" }],
1842
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1843
+ status: "complete"
1844
+ };
1845
+ }
1846
+ assertNotDisposed() {
1847
+ if (this._state.current === "disposed") {
1848
+ throw new ChatError(
1849
+ "Runtime is disposed",
1850
+ { code: "DISPOSED" /* DISPOSED */ }
1851
+ );
1852
+ }
1853
+ }
1854
+ /** Get or create adapter with retry on connection errors */
1855
+ async getOrCreateAdapterWithRetry(backend, credentials) {
1856
+ const maxAttempts = this._retryConfig?.maxAttempts ?? 1;
1857
+ const delayMs = this._retryConfig?.delayMs ?? 0;
1858
+ let lastError;
1859
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1860
+ try {
1861
+ return await this.getOrCreateAdapter(backend, credentials);
1862
+ } catch (err) {
1863
+ lastError = err instanceof Error ? err : new Error(String(err));
1864
+ if (attempt < maxAttempts) {
1865
+ const key = this.getPoolKey(backend, credentials);
1866
+ const old = this._adapterPool.get(key);
1867
+ if (old) {
1868
+ try {
1869
+ await old.dispose();
1870
+ } catch {
1871
+ }
1872
+ }
1873
+ this._adapterPool.delete(key);
1874
+ await delay(delayMs);
1875
+ }
1876
+ }
1877
+ }
1878
+ throw lastError;
1879
+ }
1880
+ /**
1881
+ * Create stream with retry for pre-stream connection errors.
1882
+ * Tries to get the first event from the stream; if that fails,
1883
+ * retries with a fresh adapter. Once first event is received,
1884
+ * the stream is committed (no more retries).
1885
+ */
1886
+ async createStreamWithRetry(adapter, session, message, options, backend, credentials) {
1887
+ const maxAttempts = this._retryConfig?.maxAttempts ?? 1;
1888
+ const delayMs = this._retryConfig?.delayMs ?? 0;
1889
+ let lastError;
1890
+ let currentAdapter = adapter;
1891
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1892
+ try {
1893
+ const stream = currentAdapter.streamMessage(session, message, options);
1894
+ const iterator = stream[Symbol.asyncIterator]();
1895
+ const first = await iterator.next();
1896
+ return (async function* () {
1897
+ if (!first.done) yield first.value;
1898
+ while (true) {
1899
+ const next = await iterator.next();
1900
+ if (next.done) break;
1901
+ yield next.value;
1902
+ }
1903
+ })();
1904
+ } catch (err) {
1905
+ lastError = err instanceof Error ? err : new Error(String(err));
1906
+ if (attempt < maxAttempts) {
1907
+ try {
1908
+ await currentAdapter.dispose();
1909
+ } catch {
1910
+ }
1911
+ const key = this.getPoolKey(backend, credentials);
1912
+ this._adapterPool.delete(key);
1913
+ await delay(delayMs);
1914
+ currentAdapter = await this.getOrCreateAdapter(backend, credentials);
1915
+ }
1916
+ }
1917
+ }
1918
+ throw lastError;
1919
+ }
1920
+ };
1921
+ function delay(ms) {
1922
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1923
+ }
1924
+ function createChatRuntime(options) {
1925
+ return new ChatRuntime(options);
1926
+ }
1927
+ var DEFAULT_PROVIDER_MODELS = {
1928
+ copilot: "gpt-5-mini",
1929
+ claude: "claude-sonnet-4-5-20250514",
1930
+ "vercel-ai": "gpt-4.1-mini"
1931
+ };
487
1932
  var MIME_TYPES = {
488
1933
  ".html": "text/html",
489
1934
  ".css": "text/css",
@@ -503,15 +1948,25 @@ var MIME_TYPES = {
503
1948
  ".map": "application/json"
504
1949
  };
505
1950
  function createChatServer(options) {
1951
+ const runtime = options.runtime ?? (options.runtimeConfig ? createChatRuntime(options.runtimeConfig) : (() => {
1952
+ throw new Error("Either `runtime` or `runtimeConfig` must be provided to createChatServer");
1953
+ })());
506
1954
  const chatPrefix = options.chatPrefix ?? "/api/chat";
507
1955
  const authPrefix = options.authPrefix ?? "/api/auth";
508
1956
  const staticPrefix = options.staticPrefix ?? "/";
509
1957
  const staticDir = options.staticDir ? path__namespace.resolve(options.staticDir) : void 0;
510
- const chatHandler = createChatHandler(options.runtime, {
1958
+ const healthPath = options.healthPath !== false ? options.healthPath ?? "/api/health" : void 0;
1959
+ const authOptions = wrapAuthWithServiceManager(
1960
+ wrapAuthWithAutoProviders(options),
1961
+ options.serviceManager
1962
+ );
1963
+ const chatHandler = createChatHandler(runtime, {
511
1964
  prefix: chatPrefix,
1965
+ providerStore: options.providers?.providerStore,
1966
+ hooks: options.hooks,
512
1967
  ...options.chatHandlerOptions
513
1968
  });
514
- const authHandler = options.auth ? createAuthHandler(options.auth) : void 0;
1969
+ const authHandler = authOptions ? createAuthHandler(authOptions) : void 0;
515
1970
  const cors = options.cors !== false ? corsMiddleware(options.cors) : void 0;
516
1971
  return async (req, res) => {
517
1972
  const url = req.url || "/";
@@ -527,6 +1982,10 @@ function createChatServer(options) {
527
1982
  return;
528
1983
  }
529
1984
  }
1985
+ if (healthPath && urlPath === healthPath) {
1986
+ json(res, { ok: true }, 200);
1987
+ return;
1988
+ }
530
1989
  if (urlPath.startsWith(chatPrefix + "/") || urlPath === chatPrefix) {
531
1990
  await chatHandler(req, res);
532
1991
  return;
@@ -563,13 +2022,51 @@ function createChatServer(options) {
563
2022
  } catch {
564
2023
  }
565
2024
  }
566
- json3(res, 404, { error: "Not found" });
2025
+ json(res, { error: "Not found" }, 404);
567
2026
  };
568
2027
  }
569
- function json3(res, status, body) {
570
- const data = JSON.stringify(body);
571
- res.writeHead(status, { "Content-Type": "application/json" });
572
- res.end(data);
2028
+ function wrapAuthWithAutoProviders(options) {
2029
+ if (!options.auth) return void 0;
2030
+ if (!options.autoCreateProviders || !options.providers) return options.auth;
2031
+ const providerStore = options.providers.providerStore;
2032
+ const modelMap = typeof options.autoCreateProviders === "object" ? options.autoCreateProviders : DEFAULT_PROVIDER_MODELS;
2033
+ const userOnAuth = options.auth.onAuth;
2034
+ const wrappedOnAuth = async (backend, token) => {
2035
+ if (userOnAuth) await userOnAuth(backend, token);
2036
+ try {
2037
+ const existing = await providerStore.list();
2038
+ const hasBackend = existing.some((p) => p.backend === backend);
2039
+ if (!hasBackend) {
2040
+ const model = modelMap[backend] ?? "default";
2041
+ const label = `${backend.charAt(0).toUpperCase() + backend.slice(1)} ${model}`;
2042
+ await providerStore.create({
2043
+ id: crypto.randomUUID(),
2044
+ backend,
2045
+ model,
2046
+ label,
2047
+ createdAt: Date.now()
2048
+ });
2049
+ }
2050
+ } catch {
2051
+ }
2052
+ };
2053
+ return { ...options.auth, onAuth: wrappedOnAuth };
2054
+ }
2055
+ function wrapAuthWithServiceManager(authOptions, serviceManager) {
2056
+ if (!authOptions || !serviceManager) return authOptions;
2057
+ const userOnAuth = authOptions.onAuth;
2058
+ const userOnLogout = authOptions.onLogout;
2059
+ return {
2060
+ ...authOptions,
2061
+ onAuth: async (backend, token) => {
2062
+ if (userOnAuth) await userOnAuth(backend, token);
2063
+ await serviceManager.handleAuth(backend, token);
2064
+ },
2065
+ onLogout: async () => {
2066
+ if (userOnLogout) await userOnLogout();
2067
+ await serviceManager.handleLogout();
2068
+ }
2069
+ };
573
2070
  }
574
2071
  var InMemoryTokenStore = class {
575
2072
  tokens = /* @__PURE__ */ new Map();
@@ -632,12 +2129,540 @@ var FileTokenStore = class {
632
2129
  return path.join(this.dir, `${provider}-token.json`);
633
2130
  }
634
2131
  };
2132
+ function createProviderHandler(options) {
2133
+ const { providerStore } = options;
2134
+ return async (req, res) => {
2135
+ const url = req.url || "";
2136
+ const method = req.method || "GET";
2137
+ const path2 = url.split("?")[0];
2138
+ const idMatch = path2.match(/^\/providers\/([^/]+)$/);
2139
+ try {
2140
+ if (method === "GET" && path2 === "/providers") {
2141
+ const providers = await providerStore.list();
2142
+ json(res, providers);
2143
+ return;
2144
+ }
2145
+ if (method === "GET" && idMatch) {
2146
+ const id = decodeURIComponent(idMatch[1]);
2147
+ const provider = await providerStore.get(id);
2148
+ if (!provider) {
2149
+ json(res, { error: "Provider not found" }, 404);
2150
+ return;
2151
+ }
2152
+ json(res, provider);
2153
+ return;
2154
+ }
2155
+ if (method === "POST" && path2 === "/providers") {
2156
+ const body = await readBody(req);
2157
+ const backend = body.backend;
2158
+ const model = body.model;
2159
+ const label = body.label;
2160
+ if (!backend || typeof backend !== "string") {
2161
+ json(res, { error: "backend is required" }, 400);
2162
+ return;
2163
+ }
2164
+ if (!model || typeof model !== "string") {
2165
+ json(res, { error: "model is required" }, 400);
2166
+ return;
2167
+ }
2168
+ if (!label || typeof label !== "string") {
2169
+ json(res, { error: "label is required" }, 400);
2170
+ return;
2171
+ }
2172
+ const config = {
2173
+ id: crypto$1.randomUUID(),
2174
+ backend,
2175
+ model,
2176
+ label,
2177
+ createdAt: Date.now()
2178
+ };
2179
+ await providerStore.create(config);
2180
+ json(res, config, 201);
2181
+ return;
2182
+ }
2183
+ if (method === "PUT" && idMatch) {
2184
+ const id = decodeURIComponent(idMatch[1]);
2185
+ const existing = await providerStore.get(id);
2186
+ if (!existing) {
2187
+ json(res, { error: "Provider not found" }, 404);
2188
+ return;
2189
+ }
2190
+ const body = await readBody(req);
2191
+ const changes = {};
2192
+ if (body.backend && typeof body.backend === "string") changes.backend = body.backend;
2193
+ if (body.model && typeof body.model === "string") changes.model = body.model;
2194
+ if (body.label && typeof body.label === "string") changes.label = body.label;
2195
+ await providerStore.update(id, changes);
2196
+ const updated = await providerStore.get(id);
2197
+ json(res, updated);
2198
+ return;
2199
+ }
2200
+ if (method === "DELETE" && idMatch) {
2201
+ const id = decodeURIComponent(idMatch[1]);
2202
+ await providerStore.delete(id);
2203
+ json(res, { ok: true });
2204
+ return;
2205
+ }
2206
+ json(res, { error: "Not found" }, 404);
2207
+ } catch (err) {
2208
+ const message = err instanceof Error ? err.message : String(err);
2209
+ json(res, { error: message }, 500);
2210
+ }
2211
+ };
2212
+ }
2213
+ var InMemoryProviderStore = class {
2214
+ providers = /* @__PURE__ */ new Map();
2215
+ async create(config) {
2216
+ const id = config.id || crypto$1.randomUUID();
2217
+ this.providers.set(id, { ...config, id });
2218
+ }
2219
+ async get(id) {
2220
+ const p = this.providers.get(id);
2221
+ return p ? { ...p } : null;
2222
+ }
2223
+ async update(id, changes) {
2224
+ const existing = this.providers.get(id);
2225
+ if (!existing) {
2226
+ throw new Error(`Provider "${id}" not found`);
2227
+ }
2228
+ this.providers.set(id, { ...existing, ...changes, id: existing.id, createdAt: existing.createdAt });
2229
+ }
2230
+ async delete(id) {
2231
+ this.providers.delete(id);
2232
+ }
2233
+ async list() {
2234
+ return [...this.providers.values()].map((p) => ({ ...p }));
2235
+ }
2236
+ };
2237
+ var FileProviderStore = class {
2238
+ dir;
2239
+ constructor(options) {
2240
+ this.dir = options.directory;
2241
+ }
2242
+ async create(config) {
2243
+ const id = config.id || crypto$1.randomUUID();
2244
+ const data = { ...config, id };
2245
+ fs.mkdirSync(this.dir, { recursive: true });
2246
+ fs.writeFileSync(this.filePath(id), JSON.stringify(data));
2247
+ }
2248
+ async get(id) {
2249
+ try {
2250
+ const data = fs.readFileSync(this.filePath(id), "utf-8");
2251
+ return JSON.parse(data);
2252
+ } catch {
2253
+ return null;
2254
+ }
2255
+ }
2256
+ async update(id, changes) {
2257
+ const existing = await this.get(id);
2258
+ if (!existing) {
2259
+ throw new Error(`Provider "${id}" not found`);
2260
+ }
2261
+ const updated = { ...existing, ...changes, id: existing.id, createdAt: existing.createdAt };
2262
+ fs.writeFileSync(this.filePath(id), JSON.stringify(updated));
2263
+ }
2264
+ async delete(id) {
2265
+ try {
2266
+ fs.unlinkSync(this.filePath(id));
2267
+ } catch {
2268
+ }
2269
+ }
2270
+ async list() {
2271
+ if (!fs.existsSync(this.dir)) return [];
2272
+ return fs.readdirSync(this.dir).filter((f) => f.endsWith("-provider.json")).map((f) => {
2273
+ try {
2274
+ const data = fs.readFileSync(path.join(this.dir, f), "utf-8");
2275
+ return JSON.parse(data);
2276
+ } catch {
2277
+ return null;
2278
+ }
2279
+ }).filter((p) => p !== null);
2280
+ }
2281
+ filePath(id) {
2282
+ return path.join(this.dir, `${id}-provider.json`);
2283
+ }
2284
+ };
2285
+
2286
+ // src/auth/refresh-manager.ts
2287
+ var TokenRefreshManager = class {
2288
+ currentToken;
2289
+ refreshFn;
2290
+ threshold;
2291
+ maxRetries;
2292
+ retryDelayMs;
2293
+ minDelayMs;
2294
+ timerId = null;
2295
+ running = false;
2296
+ disposed = false;
2297
+ listeners = {
2298
+ refreshed: /* @__PURE__ */ new Set(),
2299
+ error: /* @__PURE__ */ new Set(),
2300
+ expired: /* @__PURE__ */ new Set(),
2301
+ disposed: /* @__PURE__ */ new Set()
2302
+ };
2303
+ constructor(options) {
2304
+ this.currentToken = { ...options.token };
2305
+ this.refreshFn = options.refresh;
2306
+ this.threshold = options.refreshThreshold ?? 0.8;
2307
+ this.maxRetries = options.maxRetries ?? 3;
2308
+ this.retryDelayMs = options.retryDelayMs ?? 1e3;
2309
+ this.minDelayMs = options.minDelayMs ?? 1e3;
2310
+ }
2311
+ /** Register an event listener */
2312
+ on(event, listener) {
2313
+ this.listeners[event].add(listener);
2314
+ return this;
2315
+ }
2316
+ /** Remove an event listener */
2317
+ off(event, listener) {
2318
+ this.listeners[event].delete(listener);
2319
+ return this;
2320
+ }
2321
+ /** Current token managed by this instance */
2322
+ get token() {
2323
+ return { ...this.currentToken };
2324
+ }
2325
+ /** Whether the manager is currently running */
2326
+ get isRunning() {
2327
+ return this.running;
2328
+ }
2329
+ /** Whether the manager has been disposed */
2330
+ get isDisposed() {
2331
+ return this.disposed;
2332
+ }
2333
+ /**
2334
+ * Start automatic refresh scheduling.
2335
+ * If the token is already expired, emits "expired" immediately.
2336
+ * If the token has no expiresIn, does nothing (long-lived token).
2337
+ */
2338
+ start() {
2339
+ if (this.disposed) return;
2340
+ if (this.running) return;
2341
+ this.running = true;
2342
+ this.schedule();
2343
+ }
2344
+ /** Stop automatic refresh (can be restarted with start()) */
2345
+ stop() {
2346
+ this.running = false;
2347
+ this.clearTimer();
2348
+ }
2349
+ /**
2350
+ * Update the managed token (e.g. after manual refresh).
2351
+ * Reschedules automatic refresh if running.
2352
+ */
2353
+ updateToken(token) {
2354
+ if (this.disposed) return;
2355
+ this.currentToken = { ...token };
2356
+ if (this.running) {
2357
+ this.clearTimer();
2358
+ this.schedule();
2359
+ }
2360
+ }
2361
+ /** Stop and clean up all resources */
2362
+ dispose() {
2363
+ if (this.disposed) return;
2364
+ this.stop();
2365
+ this.disposed = true;
2366
+ this.emit("disposed");
2367
+ for (const set of Object.values(this.listeners)) {
2368
+ set.clear();
2369
+ }
2370
+ }
2371
+ // ─── Private ──────────────────────────────────────────────────
2372
+ schedule() {
2373
+ if (!this.running || this.disposed) return;
2374
+ const delayMs = this.computeRefreshDelay();
2375
+ if (delayMs === null) {
2376
+ return;
2377
+ }
2378
+ if (delayMs <= 0) {
2379
+ this.timerId = setTimeout(() => {
2380
+ this.timerId = null;
2381
+ if (!this.running || this.disposed) return;
2382
+ void this.performRefresh();
2383
+ }, 0);
2384
+ return;
2385
+ }
2386
+ this.timerId = setTimeout(() => {
2387
+ this.timerId = null;
2388
+ if (!this.running || this.disposed) return;
2389
+ void this.performRefresh();
2390
+ }, Math.max(delayMs, this.minDelayMs));
2391
+ }
2392
+ async performRefresh(attempt = 1) {
2393
+ if (!this.running || this.disposed) return;
2394
+ try {
2395
+ const newToken = await this.refreshFn(this.currentToken);
2396
+ if (!this.running || this.disposed) return;
2397
+ this.currentToken = { ...newToken };
2398
+ this.emit("refreshed", newToken);
2399
+ this.schedule();
2400
+ } catch (err) {
2401
+ if (!this.running || this.disposed) return;
2402
+ const error = err instanceof Error ? err : new Error(String(err));
2403
+ this.emit("error", error, attempt);
2404
+ if (attempt < this.maxRetries) {
2405
+ const delay2 = this.retryDelayMs * Math.pow(2, attempt - 1);
2406
+ this.timerId = setTimeout(() => {
2407
+ this.timerId = null;
2408
+ if (!this.running || this.disposed) return;
2409
+ void this.performRefresh(attempt + 1);
2410
+ }, delay2);
2411
+ } else {
2412
+ if (this.isTokenExpired()) {
2413
+ this.running = false;
2414
+ this.emit("expired");
2415
+ } else {
2416
+ const expiresIn = this.currentToken.expiresIn;
2417
+ if (expiresIn == null) return;
2418
+ const expiresAt = this.currentToken.obtainedAt + expiresIn * 1e3;
2419
+ const waitMs = Math.max(expiresAt - Date.now(), this.minDelayMs);
2420
+ this.timerId = setTimeout(() => {
2421
+ this.timerId = null;
2422
+ if (!this.running || this.disposed) return;
2423
+ void this.performRefresh();
2424
+ }, waitMs);
2425
+ }
2426
+ }
2427
+ }
2428
+ }
2429
+ computeRefreshDelay() {
2430
+ if (this.currentToken.expiresIn == null) return null;
2431
+ const lifetimeMs = this.currentToken.expiresIn * 1e3;
2432
+ const refreshAtMs = this.currentToken.obtainedAt + lifetimeMs * this.threshold;
2433
+ const now = Date.now();
2434
+ const delay2 = refreshAtMs - now;
2435
+ return delay2;
2436
+ }
2437
+ isTokenExpired() {
2438
+ if (this.currentToken.expiresIn == null) return false;
2439
+ const expiresAt = this.currentToken.obtainedAt + this.currentToken.expiresIn * 1e3;
2440
+ return Date.now() >= expiresAt;
2441
+ }
2442
+ clearTimer() {
2443
+ if (this.timerId !== null) {
2444
+ clearTimeout(this.timerId);
2445
+ this.timerId = null;
2446
+ }
2447
+ }
2448
+ emit(event, ...args) {
2449
+ for (const listener of this.listeners[event]) {
2450
+ try {
2451
+ listener(...args);
2452
+ } catch {
2453
+ }
2454
+ }
2455
+ }
2456
+ };
2457
+
2458
+ // src/chat/server/service-manager.ts
2459
+ var ServiceManager = class {
2460
+ _services = /* @__PURE__ */ new Map();
2461
+ _refreshManagers = /* @__PURE__ */ new Map();
2462
+ _options;
2463
+ constructor(options) {
2464
+ this._options = options;
2465
+ }
2466
+ /**
2467
+ * Handle auth event: dispose old service (if any) and create new one.
2468
+ * If the token is refreshable and refreshFactory is configured, starts a
2469
+ * TokenRefreshManager that auto-refreshes and recreates the service.
2470
+ */
2471
+ async handleAuth(backend, token) {
2472
+ this._stopRefreshManager(backend);
2473
+ const old = this._services.get(backend);
2474
+ if (old) {
2475
+ try {
2476
+ await old.dispose();
2477
+ } catch {
2478
+ }
2479
+ }
2480
+ const service = await this._options.createService(backend, token);
2481
+ this._services.set(backend, service);
2482
+ this._startRefreshManager(backend, token);
2483
+ return service;
2484
+ }
2485
+ /**
2486
+ * Handle logout: dispose all services, stop all refresh managers, clear cache.
2487
+ */
2488
+ async handleLogout() {
2489
+ for (const backend of [...this._refreshManagers.keys()]) {
2490
+ this._stopRefreshManager(backend);
2491
+ }
2492
+ for (const [, service] of this._services) {
2493
+ try {
2494
+ await service.dispose();
2495
+ } catch {
2496
+ }
2497
+ }
2498
+ this._services.clear();
2499
+ }
2500
+ /**
2501
+ * Dispose the ServiceManager — stops all refresh managers and disposes all services.
2502
+ */
2503
+ async dispose() {
2504
+ await this.handleLogout();
2505
+ }
2506
+ /** Get cached service for a backend (undefined if not authenticated). */
2507
+ getService(backend) {
2508
+ return this._services.get(backend);
2509
+ }
2510
+ /** Check if a service exists for the given backend. */
2511
+ hasService(backend) {
2512
+ return this._services.has(backend);
2513
+ }
2514
+ /** Get all backend names with active services. */
2515
+ get activeBackends() {
2516
+ return [...this._services.keys()];
2517
+ }
2518
+ /** Get active refresh manager for a backend (for testing/introspection). */
2519
+ getRefreshManager(backend) {
2520
+ return this._refreshManagers.get(backend);
2521
+ }
2522
+ // ── Private ─────────────────────────────────────────────────
2523
+ _startRefreshManager(backend, token) {
2524
+ if (!this._options.refreshFactory) return;
2525
+ if (token.expiresIn == null) return;
2526
+ const refreshFn = this._options.refreshFactory(backend);
2527
+ if (!refreshFn) return;
2528
+ const manager = new TokenRefreshManager({
2529
+ token,
2530
+ refresh: refreshFn,
2531
+ refreshThreshold: this._options.refreshOptions?.refreshThreshold,
2532
+ maxRetries: this._options.refreshOptions?.maxRetries,
2533
+ retryDelayMs: this._options.refreshOptions?.retryDelayMs
2534
+ });
2535
+ manager.on("refreshed", (newToken) => {
2536
+ void this._recreateService(backend, newToken);
2537
+ });
2538
+ manager.on("expired", () => {
2539
+ this._options.onTokenExpired?.(backend);
2540
+ void this._logoutBackend(backend);
2541
+ });
2542
+ this._refreshManagers.set(backend, manager);
2543
+ manager.start();
2544
+ }
2545
+ _stopRefreshManager(backend) {
2546
+ const manager = this._refreshManagers.get(backend);
2547
+ if (manager) {
2548
+ manager.dispose();
2549
+ this._refreshManagers.delete(backend);
2550
+ }
2551
+ }
2552
+ async _recreateService(backend, token) {
2553
+ const old = this._services.get(backend);
2554
+ if (old) {
2555
+ try {
2556
+ await old.dispose();
2557
+ } catch {
2558
+ }
2559
+ }
2560
+ try {
2561
+ const service = await this._options.createService(backend, token);
2562
+ this._services.set(backend, service);
2563
+ } catch {
2564
+ this._services.delete(backend);
2565
+ }
2566
+ }
2567
+ async _logoutBackend(backend) {
2568
+ this._stopRefreshManager(backend);
2569
+ const service = this._services.get(backend);
2570
+ if (service) {
2571
+ try {
2572
+ await service.dispose();
2573
+ } catch {
2574
+ }
2575
+ this._services.delete(backend);
2576
+ }
2577
+ }
2578
+ };
2579
+
2580
+ // src/chat/server/adapter-pool.ts
2581
+ var AdapterPool = class {
2582
+ _cached = /* @__PURE__ */ new Map();
2583
+ _pending = /* @__PURE__ */ new Map();
2584
+ _factory;
2585
+ _disposed = false;
2586
+ constructor(options) {
2587
+ this._factory = options.factory;
2588
+ }
2589
+ /**
2590
+ * Get or create an adapter for the given backend.
2591
+ * Concurrent calls for the same backend share one creation promise.
2592
+ * Failed creations are NOT cached — next call retries.
2593
+ */
2594
+ async getAdapter(backend) {
2595
+ if (this._disposed) {
2596
+ throw new Error("AdapterPool is disposed");
2597
+ }
2598
+ const cached = this._cached.get(backend);
2599
+ if (cached) return cached;
2600
+ const pending = this._pending.get(backend);
2601
+ if (pending) return pending;
2602
+ const promise = this._create(backend);
2603
+ this._pending.set(backend, promise);
2604
+ try {
2605
+ const adapter = await promise;
2606
+ this._cached.set(backend, adapter);
2607
+ return adapter;
2608
+ } finally {
2609
+ this._pending.delete(backend);
2610
+ }
2611
+ }
2612
+ /**
2613
+ * Evict (dispose and remove) the cached adapter for a backend.
2614
+ * Use after token rotation to force re-creation on next getAdapter().
2615
+ */
2616
+ async evict(backend) {
2617
+ const cached = this._cached.get(backend);
2618
+ if (cached) {
2619
+ this._cached.delete(backend);
2620
+ try {
2621
+ await cached.dispose();
2622
+ } catch {
2623
+ }
2624
+ }
2625
+ }
2626
+ /** Check if a backend has a cached adapter. */
2627
+ has(backend) {
2628
+ return this._cached.has(backend);
2629
+ }
2630
+ /** Get all backend names with cached adapters. */
2631
+ get activeBackends() {
2632
+ return [...this._cached.keys()];
2633
+ }
2634
+ /** Dispose all cached adapters and mark pool as unusable. */
2635
+ async dispose() {
2636
+ this._disposed = true;
2637
+ const backends = [...this._cached.keys()];
2638
+ for (const backend of backends) {
2639
+ await this.evict(backend);
2640
+ }
2641
+ }
2642
+ async _create(backend) {
2643
+ return this._factory(backend);
2644
+ }
2645
+ };
635
2646
 
2647
+ exports.AdapterPool = AdapterPool;
2648
+ exports.BodyParseError = BodyParseError;
2649
+ exports.DEFAULT_PROVIDER_MODELS = DEFAULT_PROVIDER_MODELS;
2650
+ exports.FileProviderStore = FileProviderStore;
636
2651
  exports.FileTokenStore = FileTokenStore;
2652
+ exports.InMemoryProviderStore = InMemoryProviderStore;
637
2653
  exports.InMemoryTokenStore = InMemoryTokenStore;
2654
+ exports.ServiceManager = ServiceManager;
2655
+ exports.configRoutes = configRoutes;
638
2656
  exports.corsMiddleware = corsMiddleware;
639
2657
  exports.createAuthHandler = createAuthHandler;
640
2658
  exports.createChatHandler = createChatHandler;
641
2659
  exports.createChatServer = createChatServer;
2660
+ exports.createProviderHandler = createProviderHandler;
2661
+ exports.json = json;
2662
+ exports.messageRoutes = messageRoutes;
2663
+ exports.providerRoutes = providerRoutes;
2664
+ exports.readBody = readBody;
2665
+ exports.resolveRequestContext = resolveRequestContext;
2666
+ exports.sessionRoutes = sessionRoutes;
642
2667
  //# sourceMappingURL=server.cjs.map
643
2668
  //# sourceMappingURL=server.cjs.map