@123toto/ai-app-assistant-server 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,14 +6,14 @@ import {
6
6
  testAiSdkConnection
7
7
  } from "./chunk-NIF6AW6I.js";
8
8
  import {
9
- AiDocsRequestError,
10
- createAiDocsFetchHandlers
11
- } from "./chunk-OA7OXUK7.js";
9
+ AiAppAssistantRequestError,
10
+ createAiAppAssistantFetchHandlers
11
+ } from "./chunk-Z4IVCZ5M.js";
12
12
 
13
13
  // src/assistant.ts
14
14
  import {
15
15
  PROTOCOL_VERSION,
16
- askDocumentationRequestSchema,
16
+ aiAppAssistantRequestSchema,
17
17
  generatedAnswerSchema
18
18
  } from "@123toto/ai-app-assistant-contracts";
19
19
 
@@ -81,7 +81,7 @@ function round(value) {
81
81
  var FALLBACK_CONTEXT_WINDOW_TOKENS = 128e3;
82
82
  var FALLBACK_OUTPUT_TOKENS = 8e3;
83
83
  var FALLBACK_CHARACTERS_PER_TOKEN = 2;
84
- function createDocsAssistant(options) {
84
+ function createAiAppAssistant(options) {
85
85
  const minimumEvidence = clampInteger(
86
86
  options.policies?.minimumEvidence ?? 1,
87
87
  1,
@@ -89,7 +89,7 @@ function createDocsAssistant(options) {
89
89
  );
90
90
  const documents = prepareDocuments(options.documents ?? []);
91
91
  const prepare = (request) => {
92
- const validated = askDocumentationRequestSchema.parse(request);
92
+ const validated = aiAppAssistantRequestSchema.parse(request);
93
93
  return { validated, bundle: prepareBundle(validated, documents, options) };
94
94
  };
95
95
  const finalize = (validated, bundle, generatedInput, startedAt) => {
@@ -233,7 +233,7 @@ function prepareBundle(request, documents, options) {
233
233
  content: boundEvidence(
234
234
  request.selectedElementHtml,
235
235
  selectedLimit,
236
- "AI_DOCS_SELECTED_ELEMENT_TRUNCATED"
236
+ "AI_APP_ASSISTANT_SELECTED_ELEMENT_TRUNCATED"
237
237
  ),
238
238
  relevance: 1
239
239
  });
@@ -248,7 +248,7 @@ function prepareBundle(request, documents, options) {
248
248
  for (const document of documents) {
249
249
  if (remainingDocuments <= 0) break;
250
250
  const limit = Math.min(documentLimit, remainingDocuments);
251
- const content = boundEvidence(document.content, limit, "AI_DOCS_DOCUMENT_TRUNCATED");
251
+ const content = boundEvidence(document.content, limit, "AI_APP_ASSISTANT_DOCUMENT_TRUNCATED");
252
252
  remainingDocuments -= content.length;
253
253
  items.push({
254
254
  source: "document",
@@ -275,7 +275,7 @@ function serializeDocumentationContent(content) {
275
275
  function boundHtml(content, maxChars, alreadyTruncated) {
276
276
  const limit = optionalBound(maxChars, 1e3, 8e6);
277
277
  return alreadyTruncated ? `${content.slice(0, limit)}
278
- <!-- AI_DOCS_HTML_TRUNCATED -->` : boundEvidence(content, limit, "AI_DOCS_HTML_TRUNCATED");
278
+ <!-- AI_APP_ASSISTANT_HTML_TRUNCATED -->` : boundEvidence(content, limit, "AI_APP_ASSISTANT_HTML_TRUNCATED");
279
279
  }
280
280
  function boundEvidence(content, limit, marker) {
281
281
  if (content.length <= limit) return content;
@@ -319,15 +319,15 @@ function insufficientResponse(requestId, model, durationMs) {
319
319
  }
320
320
 
321
321
  // src/node-http.ts
322
- function createAiDocsNodeHttpListener(handlers, options = {}) {
322
+ function createAiAppAssistantNodeHttpListener(handlers, options = {}) {
323
323
  return async (request, response) => {
324
324
  try {
325
325
  const webRequest = await toRequest(request, options);
326
326
  const handle = handlers.handle;
327
327
  await writeResponse(response, await handle(webRequest, request));
328
328
  } catch (error) {
329
- const status = error instanceof AiDocsRequestError ? error.status : 500;
330
- const code = error instanceof AiDocsRequestError ? error.code : "assistant_error";
329
+ const status = error instanceof AiAppAssistantRequestError ? error.status : 500;
330
+ const code = error instanceof AiAppAssistantRequestError ? error.code : "assistant_error";
331
331
  response.statusCode = status;
332
332
  response.setHeader("content-type", "application/json; charset=utf-8");
333
333
  response.end(JSON.stringify({ error: code }));
@@ -357,7 +357,7 @@ async function readBody(request, maxBodyBytes) {
357
357
  const bytes = typeof chunk === "string" ? Buffer.from(chunk) : new Uint8Array(chunk);
358
358
  size += bytes.byteLength;
359
359
  if (size > maxBodyBytes) {
360
- throw new AiDocsRequestError(413, "request_too_large", "Request body is too large");
360
+ throw new AiAppAssistantRequestError(413, "request_too_large", "Request body is too large");
361
361
  }
362
362
  chunks.push(bytes);
363
363
  }
@@ -384,22 +384,22 @@ async function writeResponse(response, webResponse) {
384
384
  }
385
385
 
386
386
  // src/server.ts
387
- function createAiDocsServer(options) {
387
+ function createAiAppAssistantServer(options) {
388
388
  const generator = options.generator ?? createGenerator(options);
389
- const assistant = createDocsAssistant({
389
+ const assistant = createAiAppAssistant({
390
390
  generator,
391
391
  ...options.documents ? { documents: options.documents } : {},
392
392
  ...options.policies ? { policies: options.policies } : {}
393
393
  });
394
394
  return {
395
395
  assistant,
396
- fetch: createAiDocsFetchHandlers({ assistant, ...options.http }),
396
+ fetch: createAiAppAssistantFetchHandlers({ assistant, ...options.http }),
397
397
  options: Object.freeze({ ...options })
398
398
  };
399
399
  }
400
400
  function createGenerator(options) {
401
401
  if (!options.model?.trim()) {
402
- throw new TypeError("createAiDocsServer requires either generator or model");
402
+ throw new TypeError("createAiAppAssistantServer requires either generator or model");
403
403
  }
404
404
  const generatorOptions = {
405
405
  model: options.model,
@@ -417,10 +417,10 @@ import { createHash as createHash2, randomUUID } from "crypto";
417
417
  // src/configuration.ts
418
418
  import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
419
419
  import { z } from "zod";
420
- var AiDocsConfigurationConflictError = class extends Error {
420
+ var AiAppAssistantConfigurationConflictError = class extends Error {
421
421
  constructor() {
422
- super("AI Docs configuration changed concurrently; retry the operation");
423
- this.name = "AiDocsConfigurationConflictError";
422
+ super("AI App Assistant configuration changed concurrently; retry the operation");
423
+ this.name = "AiAppAssistantConfigurationConflictError";
424
424
  }
425
425
  };
426
426
  var accessRuleSchema = z.discriminatedUnion("mode", [
@@ -464,8 +464,8 @@ var persistedConfigurationSchema = z.object({
464
464
  maxConversationTurns: z.number().int().min(1).max(10).optional(),
465
465
  administration: administrationSchema.optional()
466
466
  });
467
- function createAiDocsConfigurationRepository(options) {
468
- const key = options.key?.trim() || "ai-docs:configuration";
467
+ function createAiAppAssistantConfigurationRepository(options) {
468
+ const key = options.key?.trim() || "ai-app-assistant:configuration";
469
469
  const deserialize = async (serialized) => {
470
470
  if (!serialized) return void 0;
471
471
  const stored = persistedConfigurationSchema.parse(JSON.parse(serialized));
@@ -523,14 +523,14 @@ function createAiDocsConfigurationRepository(options) {
523
523
  return toConfigurationView(normalized);
524
524
  }
525
525
  }
526
- throw new AiDocsConfigurationConflictError();
526
+ throw new AiAppAssistantConfigurationConflictError();
527
527
  },
528
528
  async clear() {
529
529
  await options.store.delete(key);
530
530
  }
531
531
  };
532
532
  }
533
- async function validateAndSaveAiDocsConfiguration(repository, configuration, options) {
533
+ async function validateAndSaveAiAppAssistantConfiguration(repository, configuration, options) {
534
534
  const normalized = normalizeConfiguration(configuration);
535
535
  const connection = await testAiSdkConnection({
536
536
  model: `${normalized.provider}:${normalized.model}`,
@@ -550,7 +550,7 @@ function createAes256GcmSecretProtector(base64Key) {
550
550
  if (key.length !== 32) {
551
551
  throw new TypeError("The secret protection key must contain exactly 32 base64-encoded bytes");
552
552
  }
553
- const additionalData = Buffer.from("ai-docs-configuration:v1", "utf8");
553
+ const additionalData = Buffer.from("ai-app-assistant-configuration:v1", "utf8");
554
554
  return {
555
555
  protect(secret) {
556
556
  const iv = randomBytes(12);
@@ -580,7 +580,7 @@ function createDisabledSecretProtector() {
580
580
  };
581
581
  return { protect: unavailable2, unprotect: unavailable2 };
582
582
  }
583
- function createMemoryAiDocsStore() {
583
+ function createMemoryAiAppAssistantStore() {
584
584
  const values = /* @__PURE__ */ new Map();
585
585
  return {
586
586
  async get(key) {
@@ -600,8 +600,8 @@ function createMemoryAiDocsStore() {
600
600
  }
601
601
  };
602
602
  }
603
- function createRedisAiDocsStore(client, options) {
604
- const prefix = options?.prefix ?? "ai-docs:";
603
+ function createRedisAiAppAssistantStore(client, options) {
604
+ const prefix = options?.prefix ?? "ai-app-assistant:";
605
605
  const namespaced = (key) => `${prefix}${key}`;
606
606
  return {
607
607
  get: (key) => client.get(namespaced(key)),
@@ -679,7 +679,7 @@ function toConfigurationView(configuration) {
679
679
 
680
680
  // src/quota.ts
681
681
  import { createHash } from "crypto";
682
- function createMemoryAiDocsQuotaStore() {
682
+ function createMemoryAiAppAssistantQuotaStore() {
683
683
  const counters = /* @__PURE__ */ new Map();
684
684
  return {
685
685
  async consume(subject, policy) {
@@ -696,8 +696,8 @@ function createMemoryAiDocsQuotaStore() {
696
696
  }
697
697
  };
698
698
  }
699
- function createRedisAiDocsQuotaStore(client, options) {
700
- const prefix = options?.prefix ?? "ai-docs:quota:";
699
+ function createRedisAiAppAssistantQuotaStore(client, options) {
700
+ const prefix = options?.prefix ?? "ai-app-assistant:quota:";
701
701
  return {
702
702
  async consume(subject, policy) {
703
703
  const normalized = normalizePolicy(policy);
@@ -868,19 +868,19 @@ function isRecord(value) {
868
868
  }
869
869
 
870
870
  // src/management.ts
871
- var AiDocsManagementError = class extends Error {
871
+ var AiAppAssistantManagementError = class extends Error {
872
872
  constructor(status, code, message, details) {
873
873
  super(message);
874
874
  this.status = status;
875
875
  this.code = code;
876
876
  this.details = details;
877
- this.name = "AiDocsManagementError";
877
+ this.name = "AiAppAssistantManagementError";
878
878
  }
879
879
  status;
880
880
  code;
881
881
  details;
882
882
  };
883
- var AiDocsConfigurationManager = class {
883
+ var AiAppAssistantConfigurationManager = class {
884
884
  #repository;
885
885
  #quotaStore;
886
886
  #options;
@@ -894,7 +894,11 @@ var AiDocsConfigurationManager = class {
894
894
  constructor(options) {
895
895
  this.#options = options;
896
896
  this.#repository = options.repository;
897
- this.#quotaStore = options.quotaStore ?? createMemoryAiDocsQuotaStore();
897
+ this.#quotaStore = options.quotaStore ?? createMemoryAiAppAssistantQuotaStore();
898
+ }
899
+ /** Returns the current state of the host-controlled global kill switch. */
900
+ isEnabled() {
901
+ return typeof this.#options.enabled === "function" ? this.#options.enabled() : this.#options.enabled ?? true;
898
902
  }
899
903
  /** Returns the built-in provider catalogue; no credentials are exposed. */
900
904
  listProviders() {
@@ -902,6 +906,7 @@ var AiDocsConfigurationManager = class {
902
906
  }
903
907
  /** Discovers models with an explicit key or the currently configured secret. */
904
908
  async listModels(input) {
909
+ this.assertEnabled();
905
910
  const apiKey = await this.resolveApiKey(input.provider, input.apiKey);
906
911
  if (this.#options.listModels) {
907
912
  return this.#options.listModels({ ...input, ...apiKey ? { apiKey } : {} });
@@ -927,7 +932,10 @@ var AiDocsConfigurationManager = class {
927
932
  let connected = event.connectionValidated;
928
933
  if (event.reloadRequired) {
929
934
  this.#recentConnectionValidation = void 0;
930
- if (connected) {
935
+ if (!this.isEnabled()) {
936
+ connected = false;
937
+ this.#runtimeConnection = { status: "disabled", checkedAt: this.now() };
938
+ } else if (connected) {
931
939
  const configuration = await this.getRuntimeConfiguration();
932
940
  this.#runtimeConnection = configuration ? {
933
941
  status: "connected",
@@ -957,6 +965,7 @@ var AiDocsConfigurationManager = class {
957
965
  }
958
966
  /** Tests credentials and briefly caches a successful result for the next save. */
959
967
  async testConnection(input) {
968
+ this.assertEnabled();
960
969
  const apiKey = await this.resolveApiKey(input.provider, input.apiKey);
961
970
  const connection = this.#options.testConnection ? await this.#options.testConnection({ ...input, ...apiKey ? { apiKey } : {} }) : await testAiSdkConnection({
962
971
  model: `${input.provider}:${input.model}`,
@@ -985,6 +994,10 @@ var AiDocsConfigurationManager = class {
985
994
  /** Checks the effective stored/deployment connection used by live questions. */
986
995
  async validateRuntimeConnection() {
987
996
  this.#lastReconnectAttempt = Date.now();
997
+ if (!this.isEnabled()) {
998
+ this.#runtimeConnection = { status: "disabled", checkedAt: this.now() };
999
+ return false;
1000
+ }
988
1001
  const configuration = await this.getRuntimeConfiguration();
989
1002
  if (!configuration || configuration.provider !== "ollama" && !configuration.apiKey) {
990
1003
  this.#runtimeConnection = {
@@ -1017,7 +1030,7 @@ var AiDocsConfigurationManager = class {
1017
1030
  async save(rawInput, actor) {
1018
1031
  const input = normalizeInput(rawInput);
1019
1032
  if (input.apiKey && !this.#options.apiKeyStorageAvailable) {
1020
- throw new AiDocsManagementError(
1033
+ throw new AiAppAssistantManagementError(
1021
1034
  503,
1022
1035
  "secret_storage_unavailable",
1023
1036
  "Secure API key storage is not configured"
@@ -1027,6 +1040,7 @@ var AiDocsConfigurationManager = class {
1027
1040
  const initialActive = this.effectiveConfiguration(initial);
1028
1041
  const initialApiKey = input.apiKey ?? (initialActive?.provider === input.provider ? initialActive.apiKey : void 0) ?? this.resolveDefaultApiKey(input.provider);
1029
1042
  const initialConnectionChanged = connectionChanged(initialActive, input);
1043
+ if (!this.isEnabled() && initialConnectionChanged) throw disabled();
1030
1044
  let connection = initialConnectionChanged ? await this.validateConnectionForSave(input, initialApiKey) : this.lastKnownConnection(input.provider, input.model);
1031
1045
  if (initialConnectionChanged && !connection.success) {
1032
1046
  return { saved: false, connection, reloadRequired: false };
@@ -1091,8 +1105,8 @@ var AiDocsConfigurationManager = class {
1091
1105
  if (error instanceof ConnectionRejectedError) {
1092
1106
  return { saved: false, connection: error.connection, reloadRequired: false };
1093
1107
  }
1094
- if (error instanceof AiDocsConfigurationConflictError) {
1095
- throw new AiDocsManagementError(409, "conflict", error.message);
1108
+ if (error instanceof AiAppAssistantConfigurationConflictError) {
1109
+ throw new AiAppAssistantManagementError(409, "conflict", error.message);
1096
1110
  }
1097
1111
  throw error;
1098
1112
  }
@@ -1123,7 +1137,7 @@ var AiDocsConfigurationManager = class {
1123
1137
  try {
1124
1138
  await persist((previous) => {
1125
1139
  if (!previous?.apiKey) {
1126
- throw new AiDocsManagementError(400, "not_configured", "No manually configured API key is available to revoke");
1140
+ throw new AiAppAssistantManagementError(400, "not_configured", "No manually configured API key is available to revoke");
1127
1141
  }
1128
1142
  const owner = previous.administration?.keyCreatedBy;
1129
1143
  if (owner && owner.id !== actor.id) {
@@ -1157,8 +1171,8 @@ var AiDocsConfigurationManager = class {
1157
1171
  };
1158
1172
  });
1159
1173
  } catch (error) {
1160
- if (error instanceof AiDocsConfigurationConflictError) {
1161
- throw new AiDocsManagementError(409, "conflict", error.message);
1174
+ if (error instanceof AiAppAssistantConfigurationConflictError) {
1175
+ throw new AiAppAssistantManagementError(409, "conflict", error.message);
1162
1176
  }
1163
1177
  throw error;
1164
1178
  }
@@ -1255,6 +1269,7 @@ var AiDocsConfigurationManager = class {
1255
1269
  }
1256
1270
  /** Combines configuration, provider health and application access rules. */
1257
1271
  async canUse(identity) {
1272
+ if (!this.isEnabled()) return false;
1258
1273
  const configuration = await this.getRuntimeConfiguration();
1259
1274
  if (!configuration || configuration.provider !== "ollama" && !configuration.apiKey) return false;
1260
1275
  if (!await this.ensureRuntimeConnection()) return false;
@@ -1273,12 +1288,13 @@ var AiDocsConfigurationManager = class {
1273
1288
  }
1274
1289
  /** Enforces access and quota immediately before any model call. */
1275
1290
  async assertCanAsk(identity) {
1291
+ this.assertEnabled();
1276
1292
  if (!await this.canUse(identity)) {
1277
1293
  throw forbidden("AI assistant access is not enabled for this user");
1278
1294
  }
1279
1295
  const quota = await this.consumeQuota(identity);
1280
1296
  if (!quota.allowed) {
1281
- throw new AiDocsManagementError(
1297
+ throw new AiAppAssistantManagementError(
1282
1298
  429,
1283
1299
  "quota_reached",
1284
1300
  "AI assistant quota reached",
@@ -1288,6 +1304,7 @@ var AiDocsConfigurationManager = class {
1288
1304
  }
1289
1305
  /** Retries a failed provider lazily, with a shared backoff across requests. */
1290
1306
  async ensureRuntimeConnection() {
1307
+ if (!this.isEnabled()) return false;
1291
1308
  if (this.#runtimeConnection.status === "connected") return true;
1292
1309
  const intervalMs = Math.max(1e3, this.#options.reconnectIntervalMs ?? 3e4);
1293
1310
  if (Date.now() - this.#lastReconnectAttempt < intervalMs) return false;
@@ -1395,6 +1412,9 @@ var AiDocsConfigurationManager = class {
1395
1412
  now() {
1396
1413
  return (this.#options.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
1397
1414
  }
1415
+ assertEnabled() {
1416
+ if (!this.isEnabled()) throw disabled();
1417
+ }
1398
1418
  async publishAndEmit(event) {
1399
1419
  await this.#options.synchronizer?.publish(event);
1400
1420
  await this.emit(event);
@@ -1403,8 +1423,8 @@ var AiDocsConfigurationManager = class {
1403
1423
  await Promise.all([...this.#listeners].map((listener) => listener(event)));
1404
1424
  }
1405
1425
  };
1406
- function createPollingAiDocsConfigurationSynchronizer(store, options = {}) {
1407
- const key = options.key?.trim() || "ai-docs:configuration-revision";
1426
+ function createPollingAiAppAssistantConfigurationSynchronizer(store, options = {}) {
1427
+ const key = options.key?.trim() || "ai-app-assistant:configuration-revision";
1408
1428
  const intervalMs = Math.max(250, Math.round(options.intervalMs ?? 2e3));
1409
1429
  let current;
1410
1430
  return {
@@ -1516,11 +1536,18 @@ function configurationChanges(previous, input, allowModelChangesByOthers) {
1516
1536
  return changes;
1517
1537
  }
1518
1538
  function forbidden(message) {
1519
- return new AiDocsManagementError(403, "forbidden", message);
1539
+ return new AiAppAssistantManagementError(403, "forbidden", message);
1540
+ }
1541
+ function disabled() {
1542
+ return new AiAppAssistantManagementError(
1543
+ 503,
1544
+ "assistant_disabled",
1545
+ "AI assistant is disabled"
1546
+ );
1520
1547
  }
1521
1548
 
1522
1549
  // src/telemetry.ts
1523
- function createMemoryAiDocsTelemetryStore(options) {
1550
+ function createMemoryAiAppAssistantTelemetryStore(options) {
1524
1551
  const recentFailureLimit = normalizeLimit(options?.recentFailureLimit, 100);
1525
1552
  const aggregate = emptySummary();
1526
1553
  const failures = [];
@@ -1546,8 +1573,8 @@ function createMemoryAiDocsTelemetryStore(options) {
1546
1573
  }
1547
1574
  };
1548
1575
  }
1549
- function createRedisAiDocsTelemetryStore(client, options) {
1550
- const prefix = options?.prefix ?? "ai-docs:telemetry:";
1576
+ function createRedisAiAppAssistantTelemetryStore(client, options) {
1577
+ const prefix = options?.prefix ?? "ai-app-assistant:telemetry:";
1551
1578
  const summaryKey = `${prefix}summary`;
1552
1579
  const failuresKey = `${prefix}failures`;
1553
1580
  const recentFailureLimit = normalizeLimit(options?.recentFailureLimit, 100);
@@ -1607,7 +1634,7 @@ function createRedisAiDocsTelemetryStore(client, options) {
1607
1634
  }
1608
1635
  };
1609
1636
  }
1610
- function createAiDocsFailureEvent(input) {
1637
+ function createAiAppAssistantFailureEvent(input) {
1611
1638
  const failure = input.error instanceof AiSdkGenerationError ? input.error : normalizeAiSdkGenerationError(input.error, 1);
1612
1639
  return {
1613
1640
  outcome: "failure",
@@ -1675,7 +1702,7 @@ function redisPairs(value) {
1675
1702
  }
1676
1703
 
1677
1704
  // src/managed-runtime.ts
1678
- function createManagedAiDocsRuntime(options) {
1705
+ function createManagedAiAppAssistantRuntime(options) {
1679
1706
  let assistant;
1680
1707
  let activeGenerator;
1681
1708
  let documents = [...options.documents ?? []];
@@ -1687,6 +1714,11 @@ function createManagedAiDocsRuntime(options) {
1687
1714
  return reloadQueue;
1688
1715
  });
1689
1716
  const rebuild = async (event) => {
1717
+ if (!options.configuration.isEnabled()) {
1718
+ assistant = void 0;
1719
+ activeGenerator = void 0;
1720
+ return;
1721
+ }
1690
1722
  const connected = event.connectionValidated || await options.configuration.validateRuntimeConnection();
1691
1723
  const configuration = await options.configuration.getRuntimeConfiguration();
1692
1724
  if (!connected || !configuration) {
@@ -1706,7 +1738,7 @@ function createManagedAiDocsRuntime(options) {
1706
1738
  ...options.maxRetries !== void 0 ? { maxRetries: options.maxRetries } : {}
1707
1739
  });
1708
1740
  activeGenerator = generator;
1709
- assistant = createDocsAssistant({
1741
+ assistant = createAiAppAssistant({
1710
1742
  generator,
1711
1743
  documents,
1712
1744
  ...options.policies ? { policies: options.policies } : {}
@@ -1748,7 +1780,7 @@ function createManagedAiDocsRuntime(options) {
1748
1780
  async setDocuments(nextDocuments) {
1749
1781
  documents = [...nextDocuments];
1750
1782
  if (!activeGenerator) return;
1751
- assistant = createDocsAssistant({
1783
+ assistant = createAiAppAssistant({
1752
1784
  generator: activeGenerator,
1753
1785
  documents,
1754
1786
  ...options.policies ? { policies: options.policies } : {}
@@ -1774,7 +1806,7 @@ function createManagedAiDocsRuntime(options) {
1774
1806
  }, identity);
1775
1807
  return response;
1776
1808
  } catch (error) {
1777
- await observe(createAiDocsFailureEvent({
1809
+ await observe(createAiAppAssistantFailureEvent({
1778
1810
  error,
1779
1811
  requestId: input.requestId,
1780
1812
  operation: "answer",
@@ -1816,7 +1848,7 @@ function createManagedAiDocsRuntime(options) {
1816
1848
  yield event;
1817
1849
  }
1818
1850
  } catch (error) {
1819
- await observe(createAiDocsFailureEvent({
1851
+ await observe(createAiAppAssistantFailureEvent({
1820
1852
  error,
1821
1853
  requestId: input.requestId,
1822
1854
  operation: "stream",
@@ -1830,7 +1862,7 @@ function createManagedAiDocsRuntime(options) {
1830
1862
  };
1831
1863
  }
1832
1864
  function unavailable() {
1833
- return new AiDocsManagementError(
1865
+ return new AiAppAssistantManagementError(
1834
1866
  503,
1835
1867
  "not_configured",
1836
1868
  "AI assistant is not configured or connected"
@@ -1839,23 +1871,23 @@ function unavailable() {
1839
1871
 
1840
1872
  // src/managed-http.ts
1841
1873
  import {
1842
- aiDocsConfigurationInputSchema,
1843
- aiDocsConnectionTestInputSchema,
1844
- aiDocsCredentialsSchema,
1845
- askDocumentationRequestSchema as askDocumentationRequestSchema2
1874
+ aiAppAssistantConfigurationInputSchema,
1875
+ aiAppAssistantConnectionTestInputSchema,
1876
+ aiAppAssistantCredentialsSchema,
1877
+ aiAppAssistantRequestSchema as aiAppAssistantRequestSchema2
1846
1878
  } from "@123toto/ai-app-assistant-contracts";
1847
1879
  import { ZodError } from "zod";
1848
- function createManagedAiDocsFetchHandlers(options) {
1880
+ function createManagedAiAppAssistantFetchHandlers(options) {
1849
1881
  const identity = async (request, nativeContext) => {
1850
1882
  if (options.resolveIdentity) return options.resolveIdentity(request, nativeContext);
1851
1883
  if (options.allowAnonymous) {
1852
1884
  return { id: "anonymous", label: "Anonymous", roles: [] };
1853
1885
  }
1854
- throw new AiDocsManagementError(401, "unauthorized", "Authentication is required");
1886
+ throw new AiAppAssistantManagementError(401, "unauthorized", "Authentication is required");
1855
1887
  };
1856
1888
  const admin = async (request, resolved, nativeContext) => {
1857
1889
  if (!options.authorizeAdministration) {
1858
- throw new AiDocsManagementError(403, "forbidden", "Administration access is not configured");
1890
+ throw new AiAppAssistantManagementError(403, "forbidden", "Administration access is not configured");
1859
1891
  }
1860
1892
  await options.authorizeAdministration(resolved, request, nativeContext);
1861
1893
  };
@@ -1869,13 +1901,13 @@ function createManagedAiDocsFetchHandlers(options) {
1869
1901
  return json(await options.runtime.configuration.getAccess(currentIdentity));
1870
1902
  }
1871
1903
  if (request.method === "POST" && path.endsWith("/ask/stream")) {
1872
- const input = askDocumentationRequestSchema2.parse(await readJson(request, options.maxBodyBytes));
1904
+ const input = aiAppAssistantRequestSchema2.parse(await readJson(request, options.maxBodyBytes));
1873
1905
  const generation = options.runtime.stream(input, currentIdentity, request.signal);
1874
1906
  const first = await generation.next();
1875
1907
  return streamResponse(generation, first, input.requestId);
1876
1908
  }
1877
1909
  if (request.method === "POST" && path.endsWith("/ask")) {
1878
- const input = askDocumentationRequestSchema2.parse(await readJson(request, options.maxBodyBytes));
1910
+ const input = aiAppAssistantRequestSchema2.parse(await readJson(request, options.maxBodyBytes));
1879
1911
  return json(await options.runtime.answer(input, currentIdentity));
1880
1912
  }
1881
1913
  await admin(request, currentIdentity, nativeContext);
@@ -1909,22 +1941,22 @@ function createManagedAiDocsFetchHandlers(options) {
1909
1941
  return json({ roles, users });
1910
1942
  }
1911
1943
  if (request.method === "POST" && path.endsWith("/models")) {
1912
- const input = aiDocsCredentialsSchema.parse(await readJson(request, options.maxBodyBytes));
1944
+ const input = aiAppAssistantCredentialsSchema.parse(await readJson(request, options.maxBodyBytes));
1913
1945
  return json(await options.runtime.configuration.listModels(input));
1914
1946
  }
1915
1947
  if (request.method === "POST" && path.endsWith("/configuration/test")) {
1916
- const input = aiDocsConnectionTestInputSchema.parse(await readJson(request, options.maxBodyBytes));
1948
+ const input = aiAppAssistantConnectionTestInputSchema.parse(await readJson(request, options.maxBodyBytes));
1917
1949
  return json(await options.runtime.configuration.testConnection(input));
1918
1950
  }
1919
1951
  if (request.method === "PUT" && path.endsWith("/configuration")) {
1920
- const input = aiDocsConfigurationInputSchema.parse(await readJson(request, options.maxBodyBytes));
1952
+ const input = aiAppAssistantConfigurationInputSchema.parse(await readJson(request, options.maxBodyBytes));
1921
1953
  const { reloadRequired: _reloadRequired, ...result } = await options.runtime.configuration.save(input, currentIdentity);
1922
1954
  return json(result);
1923
1955
  }
1924
1956
  if (request.method === "DELETE" && path.endsWith("/configuration/api-key")) {
1925
1957
  return json(await options.runtime.configuration.revokeApiKey(currentIdentity));
1926
1958
  }
1927
- return json({ error: "not_found", message: "AI Docs endpoint not found" }, 404);
1959
+ return json({ error: "not_found", message: "AI App Assistant endpoint not found" }, 404);
1928
1960
  } catch (error) {
1929
1961
  if (options.onError) return options.onError(error, request, nativeContext);
1930
1962
  return mapError(error);
@@ -1935,11 +1967,11 @@ function createManagedAiDocsFetchHandlers(options) {
1935
1967
  async function readJson(request, maxBodyBytes = 86e5) {
1936
1968
  const declaredSize = Number(request.headers.get("content-length"));
1937
1969
  if (Number.isFinite(declaredSize) && declaredSize > maxBodyBytes) {
1938
- throw new AiDocsManagementError(413, "invalid_request", "Request body is too large");
1970
+ throw new AiAppAssistantManagementError(413, "invalid_request", "Request body is too large");
1939
1971
  }
1940
1972
  const text = await request.text();
1941
1973
  if (new TextEncoder().encode(text).byteLength > maxBodyBytes) {
1942
- throw new AiDocsManagementError(413, "invalid_request", "Request body is too large");
1974
+ throw new AiAppAssistantManagementError(413, "invalid_request", "Request body is too large");
1943
1975
  }
1944
1976
  return JSON.parse(text);
1945
1977
  }
@@ -1960,9 +1992,9 @@ function streamResponse(generation, first, requestId) {
1960
1992
  const failure = normalizeAiSdkGenerationError(error, 1);
1961
1993
  controller.enqueue(encoder.encode(`${JSON.stringify({
1962
1994
  type: "error",
1963
- message: error instanceof AiDocsManagementError ? error.message : "The assistant response could not be generated.",
1964
- retryable: error instanceof AiDocsManagementError ? false : failure.retryable,
1965
- ...error instanceof AiDocsManagementError ? {} : {
1995
+ message: error instanceof AiAppAssistantManagementError ? error.message : "The assistant response could not be generated.",
1996
+ retryable: error instanceof AiAppAssistantManagementError ? false : failure.retryable,
1997
+ ...error instanceof AiAppAssistantManagementError ? {} : {
1966
1998
  code: failure.code,
1967
1999
  requestId
1968
2000
  }
@@ -1982,7 +2014,7 @@ function streamResponse(generation, first, requestId) {
1982
2014
  });
1983
2015
  }
1984
2016
  function mapError(error) {
1985
- if (error instanceof AiDocsManagementError) {
2017
+ if (error instanceof AiAppAssistantManagementError) {
1986
2018
  return json({ error: error.code, message: error.message, ...error.details }, error.status);
1987
2019
  }
1988
2020
  if (error instanceof ZodError || error instanceof SyntaxError) {
@@ -2002,16 +2034,16 @@ function json(value, status = 200) {
2002
2034
  }
2003
2035
 
2004
2036
  // src/managed-server.ts
2005
- function createManagedAiDocsServer(options) {
2037
+ function createManagedAiAppAssistantServer(options) {
2006
2038
  const telemetry = resolveTelemetry(options.configuration, options.telemetry);
2007
2039
  const configuration = resolveConfiguration(options.configuration);
2008
- const runtime = createManagedAiDocsRuntime({
2040
+ const runtime = createManagedAiAppAssistantRuntime({
2009
2041
  configuration,
2010
2042
  ...options.documents ? { documents: options.documents } : {},
2011
2043
  ...options.runtime,
2012
2044
  ...telemetry ? { telemetryStore: telemetry } : {}
2013
2045
  });
2014
- const fetch = createManagedAiDocsFetchHandlers({
2046
+ const fetch = createManagedAiAppAssistantFetchHandlers({
2015
2047
  runtime,
2016
2048
  ...options.http
2017
2049
  });
@@ -2029,19 +2061,19 @@ function resolveTelemetry(configuration, telemetry) {
2029
2061
  if (telemetry === false) return void 0;
2030
2062
  if (telemetry?.store) return telemetry.store;
2031
2063
  const recentFailureLimit = telemetry?.recentFailureLimit;
2032
- if (!(configuration instanceof AiDocsConfigurationManager) && !("repository" in configuration) && configuration.storage?.type === "redis") {
2033
- return createRedisAiDocsTelemetryStore(configuration.storage.client, {
2034
- prefix: `${configuration.storage.prefix ?? "ai-docs:"}telemetry:`,
2064
+ if (!(configuration instanceof AiAppAssistantConfigurationManager) && !("repository" in configuration) && configuration.storage?.type === "redis") {
2065
+ return createRedisAiAppAssistantTelemetryStore(configuration.storage.client, {
2066
+ prefix: `${configuration.storage.prefix ?? "ai-app-assistant:"}telemetry:`,
2035
2067
  ...recentFailureLimit !== void 0 ? { recentFailureLimit } : {}
2036
2068
  });
2037
2069
  }
2038
- return createMemoryAiDocsTelemetryStore(
2070
+ return createMemoryAiAppAssistantTelemetryStore(
2039
2071
  recentFailureLimit !== void 0 ? { recentFailureLimit } : void 0
2040
2072
  );
2041
2073
  }
2042
2074
  function resolveConfiguration(configuration) {
2043
- if (configuration instanceof AiDocsConfigurationManager) return configuration;
2044
- if ("repository" in configuration) return new AiDocsConfigurationManager(configuration);
2075
+ if (configuration instanceof AiAppAssistantConfigurationManager) return configuration;
2076
+ if ("repository" in configuration) return new AiAppAssistantConfigurationManager(configuration);
2045
2077
  const {
2046
2078
  storage = { type: "memory" },
2047
2079
  encryptionKey,
@@ -2052,20 +2084,20 @@ function resolveConfiguration(configuration) {
2052
2084
  apiKeyStorageAvailable,
2053
2085
  ...manager
2054
2086
  } = configuration;
2055
- const prefix = storage.type === "redis" ? storage.prefix ?? "ai-docs:" : "ai-docs:";
2056
- const store = storage.type === "redis" ? createRedisAiDocsStore(storage.client, { prefix: `${prefix}persistent:` }) : createMemoryAiDocsStore();
2087
+ const prefix = storage.type === "redis" ? storage.prefix ?? "ai-app-assistant:" : "ai-app-assistant:";
2088
+ const store = storage.type === "redis" ? createRedisAiAppAssistantStore(storage.client, { prefix: `${prefix}persistent:` }) : createMemoryAiAppAssistantStore();
2057
2089
  const protector = secretProtector ?? (encryptionKey ? createAes256GcmSecretProtector(encryptionKey) : createDisabledSecretProtector());
2058
- return new AiDocsConfigurationManager({
2090
+ return new AiAppAssistantConfigurationManager({
2059
2091
  ...manager,
2060
- repository: createAiDocsConfigurationRepository({
2092
+ repository: createAiAppAssistantConfigurationRepository({
2061
2093
  store,
2062
2094
  secretProtector: protector,
2063
2095
  ...repositoryKey ? { key: repositoryKey } : {}
2064
2096
  }),
2065
- quotaStore: quotaStore ?? (storage.type === "redis" ? createRedisAiDocsQuotaStore(storage.client, { prefix: `${prefix}quota:` }) : createMemoryAiDocsQuotaStore()),
2097
+ quotaStore: quotaStore ?? (storage.type === "redis" ? createRedisAiAppAssistantQuotaStore(storage.client, { prefix: `${prefix}quota:` }) : createMemoryAiAppAssistantQuotaStore()),
2066
2098
  apiKeyStorageAvailable: apiKeyStorageAvailable ?? Boolean(secretProtector || encryptionKey),
2067
2099
  ...synchronizer ? { synchronizer } : storage.type === "redis" ? {
2068
- synchronizer: createPollingAiDocsConfigurationSynchronizer(store, {
2100
+ synchronizer: createPollingAiAppAssistantConfigurationSynchronizer(store, {
2069
2101
  key: "configuration-revision",
2070
2102
  intervalMs: storage.synchronizationIntervalMs ?? 2e3
2071
2103
  })
@@ -2074,17 +2106,17 @@ function resolveConfiguration(configuration) {
2074
2106
  }
2075
2107
 
2076
2108
  // src/deployment-defaults.ts
2077
- function createAiDocsDeploymentDefaults(options) {
2109
+ function createAiAppAssistantDeploymentDefaults(options) {
2078
2110
  const apiKeys = Object.fromEntries(
2079
2111
  Object.entries(options.apiKeys ?? {}).map(([provider2, value]) => [provider2, value?.trim() || void 0])
2080
2112
  );
2081
2113
  const resolveApiKey = (provider2) => apiKeys[provider2];
2082
2114
  if (!options.enabled || !options.model?.trim()) return { resolveApiKey };
2083
2115
  const match = options.model.trim().match(/^([^:/]+)[:/](.+)$/);
2084
- if (!match) throw new TypeError(`Invalid AI Docs model identifier: ${options.model}`);
2116
+ if (!match) throw new TypeError(`Invalid AI App Assistant model identifier: ${options.model}`);
2085
2117
  const provider = match[1] === "gemini" ? "google" : match[1];
2086
2118
  if (!listAiProviders().some((candidate) => candidate.id === provider)) {
2087
- throw new TypeError(`Unsupported AI Docs provider: ${match[1]}`);
2119
+ throw new TypeError(`Unsupported AI App Assistant provider: ${match[1]}`);
2088
2120
  }
2089
2121
  const apiKey = resolveApiKey(provider);
2090
2122
  const baseURL = options.baseURLs?.[provider]?.trim() || void 0;
@@ -2303,70 +2335,70 @@ function clampInteger2(value, minimum, maximum) {
2303
2335
  // src/index.ts
2304
2336
  import {
2305
2337
  PROTOCOL_VERSION as PROTOCOL_VERSION2,
2306
- aiDocsAccessRuleSchema,
2307
- aiDocsConfigurationInputSchema as aiDocsConfigurationInputSchema2,
2308
- aiDocsConfigurationOptionsSchema,
2309
- aiDocsConfigurationSaveResultSchema,
2310
- aiDocsConnectionResultSchema,
2311
- aiDocsConnectionTestInputSchema as aiDocsConnectionTestInputSchema2,
2312
- aiDocsCredentialsSchema as aiDocsCredentialsSchema2,
2313
- aiDocsManagedConfigurationViewSchema,
2314
- aiDocsModelInfoSchema,
2315
- aiDocsProviderSchema,
2316
- aiDocsProviderInfoSchema,
2317
- askDocumentationRequestSchema as askDocumentationRequestSchema3,
2318
- askDocumentationResponseSchema,
2319
- askDocumentationStreamEventSchema
2338
+ aiAppAssistantAccessRuleSchema,
2339
+ aiAppAssistantConfigurationInputSchema as aiAppAssistantConfigurationInputSchema2,
2340
+ aiAppAssistantConfigurationOptionsSchema,
2341
+ aiAppAssistantConfigurationSaveResultSchema,
2342
+ aiAppAssistantConnectionResultSchema,
2343
+ aiAppAssistantConnectionTestInputSchema as aiAppAssistantConnectionTestInputSchema2,
2344
+ aiAppAssistantCredentialsSchema as aiAppAssistantCredentialsSchema2,
2345
+ aiAppAssistantManagedConfigurationViewSchema,
2346
+ aiAppAssistantModelInfoSchema,
2347
+ aiAppAssistantProviderSchema,
2348
+ aiAppAssistantProviderInfoSchema,
2349
+ aiAppAssistantRequestSchema as aiAppAssistantRequestSchema3,
2350
+ aiAppAssistantResponseSchema,
2351
+ aiAppAssistantTransportEventSchema
2320
2352
  } from "@123toto/ai-app-assistant-contracts";
2321
2353
  export {
2322
- AiDocsConfigurationConflictError,
2323
- AiDocsConfigurationManager,
2324
- AiDocsManagementError,
2325
- AiDocsRequestError,
2354
+ AiAppAssistantConfigurationConflictError,
2355
+ AiAppAssistantConfigurationManager,
2356
+ AiAppAssistantManagementError,
2357
+ AiAppAssistantRequestError,
2326
2358
  AiModelDiscoveryError,
2327
2359
  AiSdkConfigurationError,
2328
2360
  AiSdkGenerationError,
2329
2361
  PROTOCOL_VERSION2 as PROTOCOL_VERSION,
2330
- aiDocsAccessRuleSchema,
2331
- aiDocsConfigurationInputSchema2 as aiDocsConfigurationInputSchema,
2332
- aiDocsConfigurationOptionsSchema,
2333
- aiDocsConfigurationSaveResultSchema,
2334
- aiDocsConnectionResultSchema,
2335
- aiDocsConnectionTestInputSchema2 as aiDocsConnectionTestInputSchema,
2336
- aiDocsCredentialsSchema2 as aiDocsCredentialsSchema,
2337
- aiDocsManagedConfigurationViewSchema,
2338
- aiDocsModelInfoSchema,
2339
- aiDocsProviderInfoSchema,
2340
- aiDocsProviderSchema,
2341
- askDocumentationRequestSchema3 as askDocumentationRequestSchema,
2342
- askDocumentationResponseSchema,
2343
- askDocumentationStreamEventSchema,
2362
+ aiAppAssistantAccessRuleSchema,
2363
+ aiAppAssistantConfigurationInputSchema2 as aiAppAssistantConfigurationInputSchema,
2364
+ aiAppAssistantConfigurationOptionsSchema,
2365
+ aiAppAssistantConfigurationSaveResultSchema,
2366
+ aiAppAssistantConnectionResultSchema,
2367
+ aiAppAssistantConnectionTestInputSchema2 as aiAppAssistantConnectionTestInputSchema,
2368
+ aiAppAssistantCredentialsSchema2 as aiAppAssistantCredentialsSchema,
2369
+ aiAppAssistantManagedConfigurationViewSchema,
2370
+ aiAppAssistantModelInfoSchema,
2371
+ aiAppAssistantProviderInfoSchema,
2372
+ aiAppAssistantProviderSchema,
2373
+ aiAppAssistantRequestSchema3 as aiAppAssistantRequestSchema,
2374
+ aiAppAssistantResponseSchema,
2375
+ aiAppAssistantTransportEventSchema,
2344
2376
  createAes256GcmSecretProtector,
2345
- createAiDocsConfigurationRepository,
2346
- createAiDocsDeploymentDefaults,
2347
- createAiDocsFailureEvent,
2348
- createAiDocsFetchHandlers,
2349
- createAiDocsNodeHttpListener,
2350
- createAiDocsServer,
2377
+ createAiAppAssistant,
2378
+ createAiAppAssistantConfigurationRepository,
2379
+ createAiAppAssistantDeploymentDefaults,
2380
+ createAiAppAssistantFailureEvent,
2381
+ createAiAppAssistantFetchHandlers,
2382
+ createAiAppAssistantNodeHttpListener,
2383
+ createAiAppAssistantServer,
2351
2384
  createAiSdkGenerator,
2352
2385
  createDisabledSecretProtector,
2353
- createDocsAssistant,
2354
- createManagedAiDocsFetchHandlers,
2355
- createManagedAiDocsRuntime,
2356
- createManagedAiDocsServer,
2357
- createMemoryAiDocsQuotaStore,
2358
- createMemoryAiDocsStore,
2359
- createMemoryAiDocsTelemetryStore,
2386
+ createManagedAiAppAssistantFetchHandlers,
2387
+ createManagedAiAppAssistantRuntime,
2388
+ createManagedAiAppAssistantServer,
2389
+ createMemoryAiAppAssistantQuotaStore,
2390
+ createMemoryAiAppAssistantStore,
2391
+ createMemoryAiAppAssistantTelemetryStore,
2360
2392
  createOpenAiCompatibleGenerator,
2361
- createPollingAiDocsConfigurationSynchronizer,
2362
- createRedisAiDocsQuotaStore,
2363
- createRedisAiDocsStore,
2364
- createRedisAiDocsTelemetryStore,
2393
+ createPollingAiAppAssistantConfigurationSynchronizer,
2394
+ createRedisAiAppAssistantQuotaStore,
2395
+ createRedisAiAppAssistantStore,
2396
+ createRedisAiAppAssistantTelemetryStore,
2365
2397
  filterOpenApiContext,
2366
2398
  listAiModels,
2367
2399
  listAiProviders,
2368
2400
  normalizeAiSdkGenerationError,
2369
2401
  testAiSdkConnection,
2370
- validateAndSaveAiDocsConfiguration
2402
+ validateAndSaveAiAppAssistantConfiguration
2371
2403
  };
2372
2404
  //# sourceMappingURL=index.js.map