@skillrecordings/cli 0.1.0 → 0.2.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 (136) hide show
  1. package/bin/skill.mjs +27 -0
  2. package/dist/chunk-2NCCVTEE.js +22342 -0
  3. package/dist/chunk-2NCCVTEE.js.map +1 -0
  4. package/dist/chunk-3E3GYSZR.js +7071 -0
  5. package/dist/chunk-3E3GYSZR.js.map +1 -0
  6. package/dist/chunk-F4EM72IH.js +86 -0
  7. package/dist/chunk-F4EM72IH.js.map +1 -0
  8. package/dist/chunk-FGP7KUQW.js +432 -0
  9. package/dist/chunk-FGP7KUQW.js.map +1 -0
  10. package/dist/chunk-H3D6VCME.js +55 -0
  11. package/dist/chunk-H3D6VCME.js.map +1 -0
  12. package/dist/chunk-HK3PEWFD.js +208 -0
  13. package/dist/chunk-HK3PEWFD.js.map +1 -0
  14. package/dist/chunk-KEV3QKXP.js +4495 -0
  15. package/dist/chunk-KEV3QKXP.js.map +1 -0
  16. package/dist/chunk-MG37YDAK.js +882 -0
  17. package/dist/chunk-MG37YDAK.js.map +1 -0
  18. package/dist/chunk-MLNDSBZ4.js +482 -0
  19. package/dist/chunk-MLNDSBZ4.js.map +1 -0
  20. package/dist/chunk-N2WIV2JV.js +22 -0
  21. package/dist/chunk-N2WIV2JV.js.map +1 -0
  22. package/dist/chunk-PWWRCN5W.js +2067 -0
  23. package/dist/chunk-PWWRCN5W.js.map +1 -0
  24. package/dist/chunk-SKHBM3XP.js +7746 -0
  25. package/dist/chunk-SKHBM3XP.js.map +1 -0
  26. package/dist/chunk-WFANXVQG.js +64 -0
  27. package/dist/chunk-WFANXVQG.js.map +1 -0
  28. package/dist/chunk-WYKL32C3.js +275 -0
  29. package/dist/chunk-WYKL32C3.js.map +1 -0
  30. package/dist/chunk-ZNF7XD2S.js +134 -0
  31. package/dist/chunk-ZNF7XD2S.js.map +1 -0
  32. package/dist/config-AUAIYDSI.js +20 -0
  33. package/dist/config-AUAIYDSI.js.map +1 -0
  34. package/dist/fileFromPath-XN7LXIBI.js +134 -0
  35. package/dist/fileFromPath-XN7LXIBI.js.map +1 -0
  36. package/dist/getMachineId-bsd-KW2E7VK3.js +42 -0
  37. package/dist/getMachineId-bsd-KW2E7VK3.js.map +1 -0
  38. package/dist/getMachineId-darwin-ROXJUJX5.js +42 -0
  39. package/dist/getMachineId-darwin-ROXJUJX5.js.map +1 -0
  40. package/dist/getMachineId-linux-KVZEHQSU.js +34 -0
  41. package/dist/getMachineId-linux-KVZEHQSU.js.map +1 -0
  42. package/dist/getMachineId-unsupported-PPRILPPA.js +25 -0
  43. package/dist/getMachineId-unsupported-PPRILPPA.js.map +1 -0
  44. package/dist/getMachineId-win-IIF36LEJ.js +44 -0
  45. package/dist/getMachineId-win-IIF36LEJ.js.map +1 -0
  46. package/dist/index.js +112703 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/lib-R6DEEJCP.js +7623 -0
  49. package/dist/lib-R6DEEJCP.js.map +1 -0
  50. package/dist/pipeline-IAVVAKTU.js +120 -0
  51. package/dist/pipeline-IAVVAKTU.js.map +1 -0
  52. package/dist/query-NTP5NVXN.js +25 -0
  53. package/dist/query-NTP5NVXN.js.map +1 -0
  54. package/dist/routing-BAEPFB7V.js +390 -0
  55. package/dist/routing-BAEPFB7V.js.map +1 -0
  56. package/dist/stripe-lookup-charge-EPRUMZDL.js +56 -0
  57. package/dist/stripe-lookup-charge-EPRUMZDL.js.map +1 -0
  58. package/dist/stripe-payment-history-SJPKA63N.js +67 -0
  59. package/dist/stripe-payment-history-SJPKA63N.js.map +1 -0
  60. package/dist/stripe-subscription-status-L4Z65GB3.js +58 -0
  61. package/dist/stripe-subscription-status-L4Z65GB3.js.map +1 -0
  62. package/dist/stripe-verify-refund-FZDKCIUQ.js +54 -0
  63. package/dist/stripe-verify-refund-FZDKCIUQ.js.map +1 -0
  64. package/dist/support-memory-WSG7SDKG.js +10 -0
  65. package/dist/support-memory-WSG7SDKG.js.map +1 -0
  66. package/package.json +10 -7
  67. package/.env.encrypted +0 -0
  68. package/CHANGELOG.md +0 -35
  69. package/data/tt-archive-dataset.json +0 -1
  70. package/data/validate-test-dataset.json +0 -97
  71. package/docs/CLI-AUTH.md +0 -504
  72. package/preload.ts +0 -18
  73. package/src/__tests__/init.test.ts +0 -74
  74. package/src/alignment-test.ts +0 -64
  75. package/src/check-apps.ts +0 -16
  76. package/src/commands/auth/decrypt.ts +0 -123
  77. package/src/commands/auth/encrypt.ts +0 -81
  78. package/src/commands/auth/index.ts +0 -50
  79. package/src/commands/auth/keygen.ts +0 -41
  80. package/src/commands/auth/status.ts +0 -164
  81. package/src/commands/axiom/forensic.ts +0 -868
  82. package/src/commands/axiom/index.ts +0 -697
  83. package/src/commands/build-dataset.ts +0 -311
  84. package/src/commands/db-status.ts +0 -47
  85. package/src/commands/deploys.ts +0 -219
  86. package/src/commands/eval-local/compare.ts +0 -171
  87. package/src/commands/eval-local/health.ts +0 -212
  88. package/src/commands/eval-local/index.ts +0 -76
  89. package/src/commands/eval-local/real-tools.ts +0 -416
  90. package/src/commands/eval-local/run.ts +0 -1168
  91. package/src/commands/eval-local/score-production.ts +0 -256
  92. package/src/commands/eval-local/seed.ts +0 -276
  93. package/src/commands/eval-pipeline/index.ts +0 -53
  94. package/src/commands/eval-pipeline/real-tools.ts +0 -492
  95. package/src/commands/eval-pipeline/run.ts +0 -1316
  96. package/src/commands/eval-pipeline/seed.ts +0 -395
  97. package/src/commands/eval-prompt.ts +0 -496
  98. package/src/commands/eval.test.ts +0 -253
  99. package/src/commands/eval.ts +0 -108
  100. package/src/commands/faq-classify.ts +0 -460
  101. package/src/commands/faq-cluster.ts +0 -135
  102. package/src/commands/faq-extract.ts +0 -249
  103. package/src/commands/faq-mine.ts +0 -432
  104. package/src/commands/faq-review.ts +0 -426
  105. package/src/commands/front/index.ts +0 -351
  106. package/src/commands/front/pull-conversations.ts +0 -275
  107. package/src/commands/front/tags.ts +0 -825
  108. package/src/commands/front-cache.ts +0 -1277
  109. package/src/commands/front-stats.ts +0 -75
  110. package/src/commands/health.test.ts +0 -82
  111. package/src/commands/health.ts +0 -362
  112. package/src/commands/init.test.ts +0 -89
  113. package/src/commands/init.ts +0 -106
  114. package/src/commands/inngest/client.ts +0 -294
  115. package/src/commands/inngest/events.ts +0 -296
  116. package/src/commands/inngest/investigate.ts +0 -382
  117. package/src/commands/inngest/runs.ts +0 -149
  118. package/src/commands/inngest/signal.ts +0 -143
  119. package/src/commands/kb-sync.ts +0 -498
  120. package/src/commands/memory/find.ts +0 -135
  121. package/src/commands/memory/get.ts +0 -87
  122. package/src/commands/memory/index.ts +0 -97
  123. package/src/commands/memory/stats.ts +0 -163
  124. package/src/commands/memory/store.ts +0 -49
  125. package/src/commands/memory/vote.ts +0 -159
  126. package/src/commands/pipeline.ts +0 -127
  127. package/src/commands/responses.ts +0 -856
  128. package/src/commands/tools.ts +0 -293
  129. package/src/commands/wizard.ts +0 -319
  130. package/src/index.ts +0 -172
  131. package/src/lib/crypto.ts +0 -56
  132. package/src/lib/env-loader.ts +0 -206
  133. package/src/lib/onepassword.ts +0 -137
  134. package/src/test-agent-local.ts +0 -115
  135. package/tsconfig.json +0 -11
  136. package/vitest.config.ts +0 -10
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.bun/@upstash+vector@1.2.2/node_modules/@upstash/vector/dist/nodejs.mjs","../../../node_modules/.bun/@upstash+vector@1.2.2/node_modules/@upstash/vector/dist/chunk-MQ3XJEJ2.mjs"],"sourcesContent":["import {\n FusionAlgorithm,\n HttpClient,\n Index,\n QueryMode,\n VERSION,\n WeightingStrategy\n} from \"./chunk-MQ3XJEJ2.mjs\";\n\n// src/utils/get-runtime.ts\nfunction getRuntime() {\n if (typeof process === \"object\" && typeof process.versions == \"object\" && process.versions.bun)\n return `bun@${process.versions.bun}`;\n return typeof EdgeRuntime === \"string\" ? \"edge-light\" : `node@${process.version}`;\n}\n\n// src/platforms/nodejs.ts\nvar Index2 = class _Index extends Index {\n constructor(configOrRequester) {\n if (configOrRequester !== void 0 && \"request\" in configOrRequester) {\n super(configOrRequester);\n return;\n }\n const token = configOrRequester?.token ?? process.env.NEXT_PUBLIC_UPSTASH_VECTOR_REST_TOKEN ?? process.env.UPSTASH_VECTOR_REST_TOKEN;\n const url = configOrRequester?.url ?? process.env.NEXT_PUBLIC_UPSTASH_VECTOR_REST_URL ?? process.env.UPSTASH_VECTOR_REST_URL;\n if (!token) {\n throw new Error(\"UPSTASH_VECTOR_REST_TOKEN is missing!\");\n }\n if (!url) {\n throw new Error(\"UPSTASH_VECTOR_REST_URL is missing!\");\n }\n if (url.startsWith(\" \") || url.endsWith(\" \") || /\\r|\\n/.test(url)) {\n console.warn(\"The vector url contains whitespace or newline, which can cause errors!\");\n }\n if (token.startsWith(\" \") || token.endsWith(\" \") || /\\r|\\n/.test(token)) {\n console.warn(\"The vector token contains whitespace or newline, which can cause errors!\");\n }\n const enableTelemetry = process.env.UPSTASH_DISABLE_TELEMETRY ? false : configOrRequester?.enableTelemetry ?? true;\n const telemetryHeaders = enableTelemetry ? {\n \"Upstash-Telemetry-Sdk\": `upstash-vector-js@${VERSION}`,\n \"Upstash-Telemetry-Platform\": process.env.VERCEL ? \"vercel\" : process.env.AWS_REGION ? \"aws\" : \"unknown\",\n \"Upstash-Telemetry-Runtime\": getRuntime()\n } : {};\n const client = new HttpClient({\n baseUrl: url,\n retry: configOrRequester?.retry,\n headers: { authorization: `Bearer ${token}`, ...telemetryHeaders },\n cache: configOrRequester?.cache === false ? void 0 : configOrRequester?.cache || \"no-store\",\n signal: configOrRequester?.signal\n });\n super(client);\n }\n /**\n * Create a new Upstash Vector instance from environment variables.\n *\n * Use this to automatically load connection secrets from your environment\n * variables. For instance when using the Vercel integration.\n *\n * When used on the Cloudflare Workers, you can just pass the \"env\" context provided by Cloudflare.\n * Else, this tries to load `UPSTASH_VECTOR_REST_URL` and `UPSTASH_VECTOR_REST_TOKEN` from\n * your environment using `process.env`.\n */\n static fromEnv(env, config) {\n const url = env?.UPSTASH_VECTOR_REST_URL || process?.env.UPSTASH_VECTOR_REST_URL;\n const token = env?.UPSTASH_VECTOR_REST_TOKEN || process?.env.UPSTASH_VECTOR_REST_TOKEN;\n if (!url) {\n throw new Error(\"Unable to find environment variable: `UPSTASH_VECTOR_REST_URL`\");\n }\n if (!token) {\n throw new Error(\"Unable to find environment variable: `UPSTASH_VECTOR_REST_TOKEN`\");\n }\n return new _Index({ ...config, url, token });\n }\n};\nexport {\n FusionAlgorithm,\n Index2 as Index,\n QueryMode,\n WeightingStrategy\n};\n","// src/error/index.ts\nvar UpstashError = class extends Error {\n constructor(message) {\n super(message);\n this.name = \"UpstashError\";\n }\n};\n\n// src/http/index.ts\nvar HttpClient = class {\n baseUrl;\n headers;\n options;\n retry;\n constructor(config) {\n this.options = {\n cache: config.cache,\n signal: config.signal\n };\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers\n };\n this.retry = typeof config?.retry === \"boolean\" && config?.retry === false ? {\n attempts: 1,\n backoff: () => 0\n } : {\n attempts: config?.retry?.retries ?? 5,\n backoff: config?.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50)\n };\n }\n async request(req) {\n const signal = this.options.signal;\n const isSignalFunction = typeof signal === \"function\";\n const requestOptions = {\n cache: this.options.cache,\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(req.body),\n keepalive: true,\n signal: isSignalFunction ? signal() : signal\n };\n let res = null;\n let error = null;\n for (let i = 0; i <= this.retry.attempts; i++) {\n try {\n res = await fetch([this.baseUrl, ...req.path ?? []].join(\"/\"), requestOptions);\n break;\n } catch (error_) {\n if (requestOptions.signal?.aborted && isSignalFunction) {\n throw error_;\n } else if (requestOptions.signal?.aborted) {\n const myBlob = new Blob([\n JSON.stringify({ result: requestOptions.signal.reason ?? \"Aborted\" })\n ]);\n const myOptions = {\n status: 200,\n statusText: requestOptions.signal.reason ?? \"Aborted\"\n };\n res = new Response(myBlob, myOptions);\n break;\n }\n error = error_;\n if (i < this.retry.attempts) {\n await new Promise((r) => setTimeout(r, this.retry.backoff(i)));\n }\n }\n }\n if (!res) {\n throw error ?? new Error(\"Exhausted all retries\");\n }\n const body = await res.json();\n if (!res.ok) {\n throw new UpstashError(`${body.error}`);\n }\n return { result: body.result, error: body.error };\n }\n};\n\n// src/commands/client/query/types.ts\nvar WeightingStrategy = /* @__PURE__ */ ((WeightingStrategy2) => {\n WeightingStrategy2[\"IDF\"] = \"IDF\";\n return WeightingStrategy2;\n})(WeightingStrategy || {});\nvar FusionAlgorithm = /* @__PURE__ */ ((FusionAlgorithm2) => {\n FusionAlgorithm2[\"RRF\"] = \"RRF\";\n FusionAlgorithm2[\"DBSF\"] = \"DBSF\";\n return FusionAlgorithm2;\n})(FusionAlgorithm || {});\nvar QueryMode = /* @__PURE__ */ ((QueryMode2) => {\n QueryMode2[\"HYBRID\"] = \"HYBRID\";\n QueryMode2[\"DENSE\"] = \"DENSE\";\n QueryMode2[\"SPARSE\"] = \"SPARSE\";\n return QueryMode2;\n})(QueryMode || {});\n\n// src/commands/command.ts\nvar Command = class {\n payload;\n endpoint;\n constructor(command, endpoint) {\n this.payload = command;\n this.endpoint = endpoint;\n }\n /**\n * Execute the command using a client.\n */\n async exec(client) {\n const { result, error } = await client.request({\n body: this.payload,\n path: [this.endpoint]\n });\n if (error) {\n throw new UpstashError(error);\n }\n if (result === void 0) {\n throw new TypeError(\"Request did not return a result\");\n }\n return result;\n }\n};\n\n// src/commands/client/query/query-many/index.ts\nvar QueryManyCommand = class extends Command {\n constructor(payload, options) {\n let endpoint = \"query\";\n const hasData = payload.some((p) => p.data);\n endpoint = hasData ? \"query-data\" : \"query\";\n if (options?.namespace) {\n endpoint = `${endpoint}/${options.namespace}`;\n }\n super(payload, endpoint);\n }\n};\n\n// src/commands/client/query/query-single/index.ts\nvar QueryCommand = class extends Command {\n constructor(payload, options) {\n let endpoint = \"query\";\n if (\"data\" in payload) {\n endpoint = \"query-data\";\n } else if (!payload.vector && !payload.sparseVector) {\n throw new UpstashError(\"Either data, vector or sparseVector should be provided.\");\n }\n if (options?.namespace) {\n endpoint = `${endpoint}/${options.namespace}`;\n }\n super(payload, endpoint);\n }\n};\n\n// src/commands/client/delete/index.ts\nvar DeleteCommand = class extends Command {\n constructor(payload, options) {\n let endpoint = \"delete\";\n if (options?.namespace) {\n endpoint = `${endpoint}/${options.namespace}`;\n }\n if (typeof payload === \"string\" || typeof payload === \"number\") {\n super(\n {\n ids: [payload]\n },\n endpoint\n );\n } else if (Array.isArray(payload)) {\n super(\n {\n ids: payload\n },\n endpoint\n );\n } else if (typeof payload === \"object\") {\n super(payload, endpoint);\n }\n }\n};\n\n// src/commands/client/upsert/index.ts\nvar UpsertCommand = class extends Command {\n constructor(payload, opts) {\n let endpoint = \"upsert\";\n if (Array.isArray(payload)) {\n const isUpsert = payload.some((p) => isVectorPayload(p));\n endpoint = isUpsert ? \"upsert\" : \"upsert-data\";\n } else {\n endpoint = isVectorPayload(payload) ? \"upsert\" : \"upsert-data\";\n }\n if (opts?.namespace) {\n endpoint = `${endpoint}/${opts.namespace}`;\n }\n super(payload, endpoint);\n }\n};\nvar isVectorPayload = (payload) => {\n return \"vector\" in payload || \"sparseVector\" in payload;\n};\n\n// src/commands/client/fetch/index.ts\nvar FetchCommand = class extends Command {\n constructor([payload, opts]) {\n let endpoint = \"fetch\";\n if (opts?.namespace) {\n endpoint = `${endpoint}/${opts.namespace}`;\n delete opts.namespace;\n }\n if (Array.isArray(payload)) {\n super({ ids: payload, ...opts }, endpoint);\n } else if (typeof payload === \"object\") {\n super({ ...payload, ...opts }, endpoint);\n } else {\n throw new Error(\"Invalid payload\");\n }\n }\n};\n\n// src/commands/client/range/index.ts\nvar RangeCommand = class extends Command {\n constructor(payload, options) {\n let endpoint = \"range\";\n if (options?.namespace) {\n endpoint = `${endpoint}/${options.namespace}`;\n }\n super(payload, endpoint);\n }\n};\n\n// src/commands/client/reset/index.ts\nvar ResetCommand = class extends Command {\n constructor(options) {\n let endpoint = \"reset\";\n if (options?.namespace) {\n endpoint = `${endpoint}/${options.namespace}`;\n } else if (options?.all) {\n endpoint = `${endpoint}?all`;\n }\n super([], endpoint);\n }\n};\n\n// src/commands/client/info/index.ts\nvar InfoCommand = class extends Command {\n constructor() {\n const endpoint = \"info\";\n super([], endpoint);\n }\n};\n\n// src/commands/client/resumable-query/resume.ts\nvar ResumeQueryCommand = class extends Command {\n constructor(payload) {\n super(payload, \"resumable-query-next\");\n }\n};\n\n// src/commands/client/resumable-query/start.ts\nvar StartResumableQueryCommand = class extends Command {\n constructor(payload, namespace) {\n let endpoint = \"resumable-query\";\n if (\"data\" in payload) {\n endpoint = \"resumable-query-data\";\n }\n if (namespace) {\n endpoint = `${endpoint}/${namespace}`;\n }\n super(payload, endpoint);\n }\n};\n\n// src/commands/client/resumable-query/stop.ts\nvar StopResumableQueryCommand = class extends Command {\n constructor(payload) {\n super(payload, \"resumable-query-end\");\n }\n};\n\n// src/commands/client/resumable-query/index.ts\nvar ResumableQuery = class {\n uuid;\n start;\n fetchNext;\n stop;\n constructor(payload, client, namespace) {\n this.start = async () => {\n const result = await new StartResumableQueryCommand(payload, namespace).exec(\n client\n );\n this.uuid = result.uuid;\n return result;\n };\n this.fetchNext = (additionalK) => {\n if (!this.uuid) {\n throw new Error(\n \"The resumable query has already been stopped. Please start another resumable query.\"\n );\n }\n return new ResumeQueryCommand({ uuid: this.uuid, additionalK }).exec(client);\n };\n this.stop = async () => {\n if (!this.uuid) {\n throw new Error(\"Resumable query has not been started. Call start() first.\");\n }\n const result = await new StopResumableQueryCommand({ uuid: this.uuid }).exec(client);\n this.uuid = \"\";\n return result;\n };\n }\n};\n\n// src/commands/client/namespace/index.ts\nvar Namespace = class {\n client;\n namespace;\n /**\n * Create a new index namespace client\n *\n * @example\n * ```typescript\n * const index = new Index({\n * url: \"<UPSTASH_VECTOR_REST_URL>\",\n * token: \"<UPSTASH_VECTOR_REST_TOKEN>\",\n * });\n *\n * const namespace = index.namespace(\"ns\");\n * ```\n */\n constructor(client, namespace) {\n this.client = client;\n this.namespace = namespace;\n }\n /**\n * Upserts (Updates and Inserts) specific items into the index namespace.\n * It's used for adding new items to the index namespace or updating existing ones.\n *\n * @example\n * ```js\n * const upsertArgs = {\n * id: '123',\n * vector: [0.42, 0.87, ...],\n * metadata: { property1: 'value1', property2: 'value2' }\n * };\n * const upsertResult = await index.namespace(\"ns\").upsert(upsertArgs);\n * console.log(upsertResult); // Outputs the result of the upsert operation\n * ```\n *\n * @param {CommandArgs<typeof UpsertCommand>} args - The arguments for the upsert command.\n * @param {number|string} args.id - The unique identifier for the item being upserted.\n * @param {number[]} args.vector - The feature vector associated with the item.\n * @param {Dict} [args.metadata] - Optional metadata to be associated with the item.\n *\n * @returns {string} A promise that resolves with the result of the upsert operation after the command is executed.\n */\n upsert = (args) => new UpsertCommand(args, { namespace: this.namespace }).exec(this.client);\n /*\n * Updates specific items in the index.\n * It's used for updating existing items in the index.\n *\n * @example\n * ```js\n * const updateArgs = {\n * id: '123',\n * metadata: { updatedProperty: 'value1' }\n * };\n * const updateResult = await index.update(updateArgs);\n * console.log(updateResult); // Outputs the result of the update operation\n * ```\n *\n * @param {CommandArgs<typeof UpdateCommand>} args - The arguments for the update command.\n * @param {number|string} args.id - The unique identifier for the item being updated.\n * @param {number[]} args.vector - The feature vector associated with the item.\n * @param {Record<string, unknown>} [args.metadata] - Optional metadata to be associated with the item.\n *\n * @returns {Promise<{updated: number}>} A promise that returns the number of items successfully updated.\n */\n update = (args) => new UpdateCommand(args, { namespace: this.namespace }).exec(this.client);\n /**\n * Fetches specific items from the index by their IDs or by an id prefix.\n *\n * Note: While using id prefix, the paginated `range` command is recommended to prevent timeouts on large result sets.\n *\n * @example\n * ```js\n * // Using ids\n * await index.namespace(\"ns\").fetch([\"test-1\", \"test-2\"], { includeMetadata: true });\n *\n * // Using id prefix\n * await index.namespace(\"ns\").fetch({ prefix: \"test-\" });\n * ```\n *\n * @param {...CommandArgs<typeof FetchCommand>} args - The arguments for the fetch command.\n * @param {FetchPayload} args[0] - An array of IDs or the id prefix of the items to be fetched.\n * @param {FetchCommandOptions} args[1] - Options for the fetch operation.\n * @param {boolean} [args[1].includeMetadata=false] - Optionally include metadata of the fetched items.\n * @param {boolean} [args[1].includeVectors=false] - Optionally include feature vectors of the fetched items.\n * @param {string} [args[1].namespace = \"\"] - The namespace of the index to fetch items from.\n *\n * @returns {Promise<FetchReturnResponse<TMetadata>[]>} A promise that resolves with an array of fetched items or null if not found, after the command is executed.\n */\n fetch = (...args) => {\n if (args[1]) {\n args[1].namespace = this.namespace;\n } else {\n args[1] = { namespace: this.namespace };\n }\n return new FetchCommand(args).exec(this.client);\n };\n /**\n * Queries an index namespace with specified parameters.\n * This method creates and executes a query command on an index based on the provided arguments.\n *\n * @example\n * ```js\n * await index.namespace(\"ns\").query({\n * topK: 3,\n * vector: [ 0.22, 0.66 ],\n * filter: \"age >= 23 and (type = \\'turtle\\' OR type = \\'cat\\')\"\n * });\n * ```\n *\n * @param {Object} args - The arguments for the query command.\n * @param {number[]} args.vector - An array of numbers representing the feature vector for the query.\n * This vector is utilized to find the most relevant items in the index.\n * @param {number} args.topK - The desired number of top results to be returned, based on relevance or similarity to the query vector.\n * @param {string} [args.filter] - An optional filter string to be used in the query. The filter string is used to narrow down the query results.\n * @param {boolean} [args.includeVectors=false] - When set to true, includes the feature vectors of the returned items in the response.\n * @param {boolean} [args.includeMetadata=false] - When set to true, includes additional metadata of the returned items in the response.\n *\n * @returns A promise that resolves with an array of query result objects when the request to query the index is completed.\n */\n query = (args) => new QueryCommand(args, { namespace: this.namespace }).exec(this.client);\n /**\n * Initializes a resumable query operation on the vector database.\n * This method allows for querying large result sets in multiple chunks or implementing pagination.\n *\n * @template TMetadata\n * @param {ResumableQueryPayload} args - The arguments for the resumable query.\n * @param {number} args.maxIdle - The maximum idle time in seconds before the query session expires.\n * @param {number} args.topK - The number of top results to return in each fetch operation.\n * @param {number[]} args.vector - The query vector used for similarity search.\n * @param {boolean} [args.includeMetadata] - Whether to include metadata in the query results.\n * @param {boolean} [args.includeVectors] - Whether to include vectors in the query results.\n * @param {Object} [options] - Additional options for the query.\n * @returns {Promise<ResumableQuery<TMetadata>>} A promise that resolves to a ResumableQuery object.\n * @example\n * const { result, fetchNext, stop } = await index.namespace(\"ns\").resumableQuery({\n * maxIdle: 3600,\n * topK: 50,\n * vector: [0.1, 0.2, 0.3, ...],\n * includeMetadata: true,\n * includeVectors: true\n * }, { namespace: 'my-namespace' });\n *\n * const firstBatch = await fetchNext(10);\n * const secondBatch = await fetchNext(10);\n * await stop(); // End the query session\n */\n resumableQuery = async (args) => {\n const resumableQuery = new ResumableQuery(args, this.client, this.namespace);\n const initialQuery = await resumableQuery.start();\n const { fetchNext, stop } = resumableQuery;\n return { fetchNext, stop, result: initialQuery.scores };\n };\n /**\n * Deletes items from the index namespace by id, by id prefix, or by filter.\n *\n * @example\n * ```js\n * // Delete by id\n * await index.namespace(\"ns\").delete(\"test-id\");\n \n * // Delete by ids\n * await index.namespace(\"ns\").delete([\"test-id1\", \"test-id2\"]);\n \n * // Delete by id prefix\n * await index.namespace(\"ns\").delete({ prefix: \"test-\" });\n \n * // Delete by filter\n * await index.namespace(\"ns\").delete({ filter: \"age >= 23\" });\n * ```\n *\n * @param args - A single id, an array of ids, a prefix, or a filter to delete items from the index.\n * @returns Number of deleted vectors in the format `{ deleted: number }`.If no vectors are deleted, returns `{ deleted: 0 }`.\n */\n delete = (args) => new DeleteCommand(args, { namespace: this.namespace }).exec(this.client);\n /**\n * Retrieves a paginated range of items from the index. Optionally filter results by an id prefix.\n * Returns items in batches with a cursor for pagination.\n *\n * @example\n * ```js\n * const args = {\n * limit: 10,\n * includeVectors: true,\n * includeMetadata: false\n * };\n * await index.namespace(\"ns\").range(args);\n *\n * // Use the cursor to get the next page of results\n * const nextPage = await index.namespace(\"ns\").range({\n * // You have to pass the arguments from the first call\n * ...args,\n * cursor: rangeResult.nextCursor,\n * });\n * ```\n *\n * @param {CommandArgs<typeof RangeCommand>} args - The arguments for the range command.\n * @param {string} [args.prefix] - The prefix of the items to be fetched.\n * @param {number|string} args.cursor - The starting point (cursor) for the range query.\n * @param {number} args.limit - The maximum number of items to return in this range.\n * @param {boolean} [args.includeVectors=false] - Optionally include the feature vectors of the items in the response.\n * @param {boolean} [args.includeMetadata=false] - Optionally include additional metadata of the items in the response.\n *\n * @returns {Promise<RangeReturnResponse<TMetadata>>} A promise that resolves with the response containing the next cursor and an array of vectors, after the command is executed.\n */\n range = (args) => new RangeCommand(args, { namespace: this.namespace }).exec(this.client);\n /**\n * It's used for wiping all the vectors in a index namespace.\n *\n * @example\n * ```js\n * await index.namespace(\"ns\").reset();\n * console.log('Index namespace has been reset');\n * ```\n *\n * @returns {Promise<string>} A promise that resolves with the result of the reset operation after the command is executed.\n */\n reset = () => new ResetCommand({ namespace: this.namespace }).exec(this.client);\n};\n\n// src/commands/client/update/index.ts\nvar UpdateCommand = class extends Command {\n constructor(payload, opts) {\n let endpoint = \"update\";\n if (opts?.namespace) {\n endpoint = `${endpoint}/${opts.namespace}`;\n }\n super(payload, endpoint);\n }\n};\n\n// src/commands/management/namespaces/list/index.ts\nvar ListNamespacesCommand = class extends Command {\n constructor() {\n const endpoint = \"list-namespaces\";\n super([], endpoint);\n }\n};\n\n// src/commands/management/namespaces/delete/index.ts\nvar DeleteNamespaceCommand = class extends Command {\n constructor(namespace) {\n const endpoint = `delete-namespace/${namespace}`;\n super([], endpoint);\n }\n};\n\n// src/vector.ts\nvar Index = class {\n client;\n /**\n * Create a new vector db client\n *\n * @example\n * ```typescript\n * const index = new Index({\n * url: \"<UPSTASH_VECTOR_REST_URL>\",\n * token: \"<UPSTASH_VECTOR_REST_TOKEN>\",\n * });\n * ```\n */\n constructor(client) {\n this.client = client;\n }\n namespace = (namespace) => new Namespace(this.client, namespace);\n /**\n * Deletes items from the index by id, by id prefix, or by filter.\n *\n * @example\n * ```js\n * // Delete by id\n * await index.delete(\"test-id\");\n \n * // Delete by ids\n * await index.delete([\"test-id1\", \"test-id2\"]);\n \n * // Delete by id prefix\n * await index.delete({ prefix: \"test-\" });\n \n * // Delete by filter\n * await index.delete({ filter: \"age >= 23\" });\n * ```\n *\n * @param args - A single id, an array of ids, a prefix, or a filter to delete items from the index.\n * @returns Number of deleted vectors in the format `{ deleted: number }`.If no vectors are deleted, returns `{ deleted: 0 }`.\n */\n delete = (args, options) => new DeleteCommand(args, options).exec(this.client);\n /**\n * Queries an index with specified parameters.\n * This method creates and executes a query command on an index based on the provided arguments.\n *\n * @example\n * ```js\n * await index.query({\n * topK: 3,\n * vector: [ 0.22, 0.66 ],\n * filter: \"age >= 23 and (type = \\'turtle\\' OR type = \\'cat\\')\"\n * });\n * ```\n *\n * @param {Object} args - The arguments for the query command.\n * @param {number[]} args.vector - An array of numbers representing the feature vector for the query.\n * This vector is utilized to find the most relevant items in the index.\n * @param {number} args.topK - The desired number of top results to be returned, based on relevance or similarity to the query vector.\n * @param {string} [args.filter] - An optional filter string to be used in the query. The filter string is used to narrow down the query results.\n * @param {boolean} [args.includeVectors=false] - When set to true, includes the feature vectors of the returned items in the response.\n * @param {boolean} [args.includeMetadata=false] - When set to true, includes additional metadata of the returned items in the response.\n * @param {boolean} [args.includeData=false] - When set to true, includes data - string - of the returned items in the response.\n *\n * A promise that resolves with an array of query result objects when the request to query the index is completed.\n */\n query = (args, options) => new QueryCommand(args, options).exec(this.client);\n /**\n * Queries an index with specified parameters.\n * This method creates and executes a query command on an index based on the provided arguments.\n *\n * @example\n * ```js\n * await index.queryMany([\n * {\n * topK: 3,\n * vector: [0.22, 0.66],\n * filter: \"age >= 23 and (type = 'turtle' OR type = 'cat')\",\n * },\n * {\n * topK: 3,\n * vector: [0.45, 0.52],\n * filter: \"age >= 27 and (type = 'rabbit' OR type = 'dog')\",\n * },\n * ]);\n *\n * ```\n *\n * @param {Object} args - The arguments for the query command.\n * @param {number[]} args.vector - An array of numbers representing the feature vector for the query.\n * This vector is utilized to find the most relevant items in the index.\n * @param {number} args.topK - The desired number of top results to be returned, based on relevance or similarity to the query vector.\n * @param {string} [args.filter] - An optional filter string to be used in the query. The filter string is used to narrow down the query results.\n * @param {boolean} [args.includeVectors=false] - When set to true, includes the feature vectors of the returned items in the response.\n * @param {boolean} [args.includeMetadata=false] - When set to true, includes additional metadata of the returned items in the response.\n * @param {boolean} [args.includeData=false] - When set to true, includes data - string - of the returned items in the response.\n *\n * A promise that resolves with an array of arrays of query result objects,\n * where each inner array represents a group of results matching a specific query condition.\n */\n queryMany = (args, options) => new QueryManyCommand(args, options).exec(this.client);\n /**\n * Initializes a resumable query operation on the vector database.\n * This method allows for querying large result sets in multiple chunks or implementing pagination.\n *\n * @template TMetadata\n * @param {ResumableQueryPayload} args - The arguments for the resumable query.\n * @param {number} args.maxIdle - The maximum idle time in seconds before the query session expires.\n * @param {number} args.topK - The number of top results to return in each fetch operation.\n * @param {number[]} args.vector - The query vector used for similarity search.\n * @param {boolean} [args.includeMetadata] - Whether to include metadata in the query results.\n * @param {boolean} [args.includeVectors] - Whether to include vectors in the query results.\n * @param {Object} [options] - Additional options for the query.\n * @param {string} [options.namespace] - The namespace to query within.\n * @returns {Promise<ResumableQuery<TMetadata>>} A promise that resolves to a ResumableQuery object.\n * @example\n * const { result, fetchNext, stop } = await index.resumableQuery({\n * maxIdle: 3600,\n * topK: 50,\n * vector: [0.1, 0.2, 0.3, ...],\n * includeMetadata: true,\n * includeVectors: true\n * }, { namespace: 'my-namespace' });\n *\n * const firstBatch = await fetchNext(10);\n * const secondBatch = await fetchNext(10);\n * await stop(); // End the query session\n */\n resumableQuery = async (args, options) => {\n const resumableQuery = new ResumableQuery(args, this.client, options?.namespace);\n const initialQuery = await resumableQuery.start();\n const { fetchNext, stop } = resumableQuery;\n return { fetchNext, stop, result: initialQuery.scores };\n };\n /**\n * Upserts (Updates and Inserts) specific items into the index.\n * It's used for adding new items to the index or updating existing ones.\n *\n * @example\n * ```js\n * const upsertArgs = {\n * id: '123',\n * vector: [0.42, 0.87, ...],\n * metadata: { property1: 'value1', property2: 'value2' }\n * };\n * const upsertResult = await index.upsert(upsertArgs);\n * console.log(upsertResult); // Outputs the result of the upsert operation\n * ```\n *\n * @param {CommandArgs<typeof UpsertCommand>} args - The arguments for the upsert command.\n * @param {number|string} args.id - The unique identifier for the item being upserted.\n * @param {number[]} args.vector - The feature vector associated with the item.\n * @param {Record<string, unknown>} [args.metadata] - Optional metadata to be associated with the item.\n *\n * @returns {string} A promise that resolves with the result of the upsert operation after the command is executed.\n */\n upsert = (args, options) => new UpsertCommand(args, options).exec(this.client);\n /*\n * Updates specific items in the index.\n * It's used for updating existing items in the index.\n *\n * @example\n * ```js\n * const updateArgs = {\n * id: '123',\n * vector: [0.42, 0.87, ...],\n * metadata: { property1: 'value1', property2: 'value2' }\n * };\n * const updateResult = await index.update(updateArgs);\n * console.log(updateResult); // Outputs the result of the update operation\n * ```\n *\n * @param {CommandArgs<typeof UpdateCommand>} args - The arguments for the update command.\n * @param {number|string} args.id - The unique identifier for the item being updated.\n * @param {number[]} args.vector - The feature vector associated with the item.\n * @param {Record<string, unknown>} [args.metadata] - Optional metadata to be associated with the item.\n * @param {string} [args.namespace] - The namespace to update the item in.\n *\n * @returns {Promise<{updated: number}>} A promise that returns the number of items successfully updated.\n */\n update = (args, options) => new UpdateCommand(args, options).exec(this.client);\n /**\n * Fetches specific items from the index by their IDs or by an id prefix.\n *\n * Note: While using id prefix, the paginated `range` command is recommended to prevent timeouts on large result sets.\n *\n * @example\n * ```js\n * // Using ids\n * await index.fetch([\"test-1\", \"test-2\"], { includeMetadata: true });\n *\n * // Using id prefix\n * await index.fetch({ prefix: \"test-\" });\n * ```\n *\n * @param {...CommandArgs<typeof FetchCommand>} args - The arguments for the fetch command.\n * @param {FetchPayload} args[0] - An array of IDs or the id prefix of the items to be fetched.\n * @param {FetchCommandOptions} args[1] - Options for the fetch operation.\n * @param {boolean} [args[1].includeMetadata=false] - Optionally include metadata of the fetched items.\n * @param {boolean} [args[1].includeVectors=false] - Optionally include feature vectors of the fetched items.\n * @param {string} [args[1].namespace = \"\"] - The namespace of the index to fetch items from.\n *\n * @returns {Promise<FetchReturnResponse<TMetadata>[]>} A promise that resolves with an array of fetched items or null if not found, after the command is executed.\n */\n fetch = (...args) => new FetchCommand(args).exec(this.client);\n /**\n * It's used for wiping the index.\n *\n * By default, resets the default namespace:\n *\n * @example\n * ```js\n * await index.reset();\n * console.log('Default namespace has been reset');\n * ```\n *\n * To reset a namespace, call reset like:\n *\n * @example\n * ```js\n * await index.reset({ namespace: \"ns\" });\n * console.log('Namespace ns has been reset');\n * ```\n *\n * If you want to reset all namespaces, call reset like:\n *\n * @example\n * ```js\n * await index.reset({ all: true });\n * console.log('All namespaces have been reset');\n * ```\n *\n * @returns {Promise<string>} A promise that resolves with the result of the reset operation after the command is executed.\n */\n reset = (options) => new ResetCommand(options).exec(this.client);\n /**\n * Retrieves a paginated range of items from the index. Optionally filter results by an id prefix.\n * Returns items in batches with a cursor for pagination.\n *\n * @example\n * ```js\n * const args = {\n * limit: 10,\n * includeVectors: true,\n * includeMetadata: false\n * };\n * await index.range(args);\n *\n * // Use the cursor to get the next page of results\n * const nextPage = await index.range({\n * // You have to pass the arguments from the first call\n * ...args,\n * cursor: rangeResult.nextCursor,\n * });\n * ```\n *\n * @param {CommandArgs<typeof RangeCommand>} args - The arguments for the range command.\n * @param {string} [args.prefix] - The prefix of the items to be fetched.\n * @param {number|string} args.cursor - The starting point (cursor) for the range query.\n * @param {number} args.limit - The maximum number of items to return in this range.\n * @param {boolean} [args.includeVectors=false] - Optionally include the feature vectors of the items in the response.\n * @param {boolean} [args.includeMetadata=false] - Optionally include additional metadata of the items in the response.\n *\n * @returns {Promise<RangeReturnResponse<TMetadata>>} A promise that resolves with the response containing the next cursor and an array of vectors, after the command is executed.\n */\n range = (args, options) => new RangeCommand(args, options).exec(this.client);\n /**\n * Retrieves info from the index.\n *\n * @example\n * ```js\n * const infoResults = await index.info();\n * console.log(infoResults); // Outputs the result of the info operation\n * ```\n *\n * @returns {Promise<InfoResult>} A promise that resolves with the response containing the vectorCount, pendingVectorCount, indexSize, dimension count and similarity algorithm after the command is executed.\n */\n info = () => new InfoCommand().exec(this.client);\n /**\n * List all namespaces in the vector database.\n *\n * @example\n * ```js\n * const namespaces = await index.listNamespaces();\n * console.log(namespaces); // Outputs the list of namespaces\n * ```\n *\n * @returns {Promise<string[]>} A promise that resolves with an array of namespaces after the command is executed.\n */\n listNamespaces = () => new ListNamespacesCommand().exec(this.client);\n /**\n * Deletes a namespace from the vector database.\n *\n * @example\n * ```js\n * await index.deleteNamespace('namespace');\n * console.log('Namespace has been deleted');\n * ```\n *\n * @param {string} namespace - The name of the namespace to be deleted.\n * @returns {Promise<string>} A promise that resolves with the result of the delete operation after the command is executed.\n */\n deleteNamespace = (namespace) => new DeleteNamespaceCommand(namespace).exec(this.client);\n};\n\n// version.ts\nvar VERSION = \"v1.2.2\";\n\nexport {\n HttpClient,\n WeightingStrategy,\n FusionAlgorithm,\n QueryMode,\n Index,\n VERSION\n};\n"],"mappings":";;;;;AAAA;;;ACAA;AACA,IAAI,eAAe,cAAc,MAAM;AAAA,EACrC,YAAY,SAAS;AACnB,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGA,IAAI,aAAa,MAAM;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,QAAQ;AAClB,SAAK,UAAU;AAAA,MACb,OAAO,OAAO;AAAA,MACd,QAAQ,OAAO;AAAA,IACjB;AACA,SAAK,UAAU,OAAO,QAAQ,QAAQ,OAAO,EAAE;AAC/C,SAAK,UAAU;AAAA,MACb,gBAAgB;AAAA,MAChB,GAAG,OAAO;AAAA,IACZ;AACA,SAAK,QAAQ,OAAO,QAAQ,UAAU,aAAa,QAAQ,UAAU,QAAQ;AAAA,MAC3E,UAAU;AAAA,MACV,SAAS,MAAM;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0E;AAAA,IACzF;AACA,UAAM,kBAAkB,QAAQ,IAAI,4BAA4B,QAAQ,mBAAmB,mBAAmB;AAC9G,UAAM,mBAAmB,kBAAkB;AAAA,MACzC,yBAAyB,qBAAqB,OAAO;AAAA,MACrD,8BAA8B,QAAQ,IAAI,SAAS,WAAW,QAAQ,IAAI,aAAa,QAAQ;AAAA,MAC/F,6BAA6B,WAAW;AAAA,IAC1C,IAAI,CAAC;AACL,UAAM,SAAS,IAAI,WAAW;AAAA,MAC5B,SAAS;AAAA,MACT,OAAO,mBAAmB;AAAA,MAC1B,SAAS,EAAE,eAAe,UAAU,KAAK,IAAI,GAAG,iBAAiB;AAAA,MACjE,OAAO,mBAAmB,UAAU,QAAQ,SAAS,mBAAmB,SAAS;AAAA,MACjF,QAAQ,mBAAmB;AAAA,IAC7B,CAAC;AACD,UAAM,MAAM;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,OAAO,QAAQ,KAAK,QAAQ;AAC1B,UAAM,MAAM,KAAK,2BAA2B,SAAS,IAAI;AACzD,UAAM,QAAQ,KAAK,6BAA6B,SAAS,IAAI;AAC7D,QAAI,CAAC,KAAK;AACR,YAAM,IAAI,MAAM,gEAAgE;AAAA,IAClF;AACA,QAAI,CAAC,OAAO;AACV,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AACA,WAAO,IAAI,OAAO,EAAE,GAAG,QAAQ,KAAK,MAAM,CAAC;AAAA,EAC7C;AACF;","names":[]}
@@ -0,0 +1,482 @@
1
+ import {
2
+ Index2
3
+ } from "./chunk-MG37YDAK.js";
4
+ import {
5
+ init_esm_shims
6
+ } from "./chunk-WFANXVQG.js";
7
+
8
+ // ../memory/src/decay.ts
9
+ init_esm_shims();
10
+ var DECAY_HALF_LIFE_DAYS = 30;
11
+ function calculateDecay(createdAt, lastValidatedAt) {
12
+ const referenceDate = lastValidatedAt || createdAt;
13
+ const ageDays = (Date.now() - referenceDate.getTime()) / (24 * 60 * 60 * 1e3);
14
+ return Math.pow(0.5, ageDays / DECAY_HALF_LIFE_DAYS);
15
+ }
16
+ function calculateConfidence(memory) {
17
+ const decay = calculateDecay(
18
+ new Date(memory.metadata.created_at),
19
+ memory.metadata.last_validated_at ? new Date(memory.metadata.last_validated_at) : void 0
20
+ );
21
+ const votes = memory.metadata.votes;
22
+ const totalVotes = votes.upvotes + votes.downvotes;
23
+ const voteScore = totalVotes > 0 ? (votes.upvotes - votes.downvotes) / totalVotes : 0;
24
+ const citationScore = votes.citations > 0 ? votes.success_rate : 0.5;
25
+ const reputationWeight = Math.min(totalVotes + votes.citations, 10) / 10;
26
+ const reputation = (voteScore * 0.3 + citationScore * 0.7) * reputationWeight + (1 - reputationWeight) * 0.5;
27
+ return decay * reputation;
28
+ }
29
+
30
+ // ../memory/src/client.ts
31
+ init_esm_shims();
32
+ var _index = null;
33
+ function getVectorIndex() {
34
+ if (!_index) {
35
+ const url = process.env.UPSTASH_VECTOR_REST_URL;
36
+ const token = process.env.UPSTASH_VECTOR_REST_TOKEN;
37
+ if (!url) {
38
+ throw new Error(
39
+ "UPSTASH_VECTOR_REST_URL environment variable is required"
40
+ );
41
+ }
42
+ if (!token) {
43
+ throw new Error(
44
+ "UPSTASH_VECTOR_REST_TOKEN environment variable is required"
45
+ );
46
+ }
47
+ _index = new Index2({
48
+ url,
49
+ token
50
+ });
51
+ }
52
+ return _index;
53
+ }
54
+ async function upsertMemory(memory) {
55
+ const index = getVectorIndex();
56
+ return index.upsert(
57
+ {
58
+ id: memory.id,
59
+ data: memory.content,
60
+ // Upstash generates embedding from data string
61
+ metadata: memory.metadata
62
+ },
63
+ { namespace: memory.metadata.collection }
64
+ );
65
+ }
66
+ async function queryMemories(options) {
67
+ const index = getVectorIndex();
68
+ const { query, collection, topK = 10, filter } = options;
69
+ const results = await index.query(
70
+ {
71
+ data: query,
72
+ // Upstash generates embedding from query string
73
+ topK,
74
+ includeMetadata: true,
75
+ ...filter && { filter }
76
+ },
77
+ { namespace: collection }
78
+ );
79
+ return results.map((result) => ({
80
+ id: String(result.id),
81
+ score: result.score,
82
+ metadata: result.metadata
83
+ }));
84
+ }
85
+ async function deleteMemory(id, collection) {
86
+ const index = getVectorIndex();
87
+ await index.delete(id, { namespace: collection });
88
+ }
89
+ async function fetchMemory(id, collection) {
90
+ const index = getVectorIndex();
91
+ const results = await index.fetch([id], {
92
+ namespace: collection,
93
+ includeMetadata: true,
94
+ includeData: true
95
+ });
96
+ if (results.length === 0) {
97
+ return null;
98
+ }
99
+ const result = results[0];
100
+ if (!result) {
101
+ return null;
102
+ }
103
+ return {
104
+ id: String(result.id),
105
+ content: String(result.data),
106
+ metadata: result.metadata
107
+ };
108
+ }
109
+
110
+ // ../memory/src/memory.ts
111
+ init_esm_shims();
112
+ import { randomUUID } from "crypto";
113
+ var MemoryService = {
114
+ /**
115
+ * Store a new memory with embedding generation
116
+ *
117
+ * @param content - The memory content to store
118
+ * @param metadata - Memory metadata (collection and source required)
119
+ * @returns The created memory with generated ID and timestamps
120
+ */
121
+ async store(content, metadata) {
122
+ const now = (/* @__PURE__ */ new Date()).toISOString();
123
+ const memory = {
124
+ id: randomUUID(),
125
+ content,
126
+ metadata: {
127
+ collection: metadata.collection,
128
+ source: metadata.source,
129
+ app_slug: metadata.app_slug,
130
+ tags: metadata.tags ?? [],
131
+ confidence: metadata.confidence ?? 1,
132
+ created_at: metadata.created_at ?? now,
133
+ last_validated_at: metadata.last_validated_at,
134
+ votes: metadata.votes ?? {
135
+ upvotes: 0,
136
+ downvotes: 0,
137
+ citations: 0,
138
+ success_rate: 0
139
+ }
140
+ }
141
+ };
142
+ await upsertMemory(memory);
143
+ return memory;
144
+ },
145
+ /**
146
+ * Find memories by semantic similarity
147
+ *
148
+ * Queries the vector index, fetches full memory data, calculates
149
+ * confidence with time decay, filters by threshold, and sorts by final score.
150
+ *
151
+ * @param query - Search query text
152
+ * @param options - Search options including filters and limits
153
+ * @returns Array of search results with decay-adjusted scores
154
+ */
155
+ async find(query, options) {
156
+ const {
157
+ collection,
158
+ limit = 10,
159
+ threshold = 0.5,
160
+ app_slug,
161
+ tags,
162
+ include_stale = false
163
+ } = options;
164
+ let filter;
165
+ if (app_slug || tags) {
166
+ const filters = [];
167
+ if (app_slug) {
168
+ filters.push(`app_slug = "${app_slug}"`);
169
+ }
170
+ if (tags && tags.length > 0) {
171
+ tags.forEach((tag) => {
172
+ filters.push(`tags[*] = "${tag}"`);
173
+ });
174
+ }
175
+ filter = filters.join(" AND ");
176
+ }
177
+ const queryResults = await queryMemories({
178
+ query,
179
+ collection,
180
+ topK: limit * 2,
181
+ // Over-fetch to account for filtering
182
+ filter
183
+ });
184
+ const results = [];
185
+ for (const result of queryResults) {
186
+ const memory = await fetchMemory(result.id, collection);
187
+ if (!memory) continue;
188
+ const confidence = calculateConfidence(memory);
189
+ if (!include_stale && confidence < 0.25) continue;
190
+ const createdAt = new Date(memory.metadata.created_at);
191
+ const lastValidatedAt = memory.metadata.last_validated_at ? new Date(memory.metadata.last_validated_at) : void 0;
192
+ const referenceDate = lastValidatedAt || createdAt;
193
+ const ageDays = (Date.now() - referenceDate.getTime()) / (24 * 60 * 60 * 1e3);
194
+ const decayFactor = Math.pow(0.5, ageDays / 30);
195
+ const finalScore = result.score * confidence;
196
+ if (finalScore < threshold) continue;
197
+ results.push({
198
+ memory,
199
+ score: finalScore,
200
+ raw_score: result.score,
201
+ age_days: ageDays,
202
+ decay_factor: decayFactor
203
+ });
204
+ }
205
+ results.sort((a, b) => b.score - a.score);
206
+ return results.slice(0, limit);
207
+ },
208
+ /**
209
+ * Get a specific memory by ID
210
+ *
211
+ * @param id - Memory ID
212
+ * @param collection - Collection the memory belongs to
213
+ * @returns The memory or null if not found
214
+ */
215
+ async get(id, collection) {
216
+ return fetchMemory(id, collection);
217
+ },
218
+ /**
219
+ * Delete a memory
220
+ *
221
+ * @param id - Memory ID to delete
222
+ * @param collection - Collection the memory belongs to
223
+ */
224
+ async delete(id, collection) {
225
+ await deleteMemory(id, collection);
226
+ },
227
+ /**
228
+ * Validate a memory (resets decay clock)
229
+ *
230
+ * Updates the last_validated_at timestamp to the current time,
231
+ * which resets the time-based decay calculation.
232
+ *
233
+ * @param id - Memory ID to validate
234
+ * @param collection - Collection the memory belongs to
235
+ * @throws {Error} If memory not found
236
+ */
237
+ async validate(id, collection) {
238
+ const memory = await fetchMemory(id, collection);
239
+ if (!memory) {
240
+ throw new Error("Memory not found");
241
+ }
242
+ memory.metadata.last_validated_at = (/* @__PURE__ */ new Date()).toISOString();
243
+ await upsertMemory(memory);
244
+ }
245
+ };
246
+
247
+ // ../memory/src/voting.ts
248
+ init_esm_shims();
249
+ var VotingService = {
250
+ /**
251
+ * Vote on a memory (upvote or downvote)
252
+ *
253
+ * @param id - Memory ID
254
+ * @param collection - Collection the memory belongs to
255
+ * @param voteType - Type of vote ('upvote' or 'downvote')
256
+ * @throws {Error} If memory not found
257
+ */
258
+ async vote(id, collection, voteType) {
259
+ const memory = await fetchMemory(id, collection);
260
+ if (!memory) {
261
+ throw new Error("Memory not found");
262
+ }
263
+ if (voteType === "upvote") {
264
+ memory.metadata.votes.upvotes++;
265
+ } else {
266
+ memory.metadata.votes.downvotes++;
267
+ }
268
+ await upsertMemory(memory);
269
+ },
270
+ /**
271
+ * Record a citation (memories were retrieved and used)
272
+ *
273
+ * @param memoryIds - Array of memory IDs
274
+ * @param runId - Run ID for tracking citation context
275
+ * @param collection - Collection the memories belong to
276
+ * @throws {Error} If any memory not found or memoryIds is empty
277
+ */
278
+ async cite(memoryIds, runId, collection) {
279
+ if (memoryIds.length === 0) {
280
+ throw new Error("memoryIds cannot be empty");
281
+ }
282
+ for (const id of memoryIds) {
283
+ const memory = await fetchMemory(id, collection);
284
+ if (!memory) {
285
+ throw new Error("Memory not found");
286
+ }
287
+ memory.metadata.votes.citations++;
288
+ await upsertMemory(memory);
289
+ }
290
+ },
291
+ /**
292
+ * Record outcome for citations (success or failure)
293
+ *
294
+ * Updates the success_rate based on accumulated outcomes.
295
+ * Formula: success_rate = success_count / total_outcomes
296
+ *
297
+ * We store outcome counts in metadata (not in schema yet, but will add).
298
+ * For now, we store them as custom fields in metadata.
299
+ *
300
+ * @param memoryIds - Array of memory IDs
301
+ * @param runId - Run ID for tracking outcome context
302
+ * @param outcome - Outcome type ('success' or 'failure')
303
+ * @param collection - Collection the memories belong to
304
+ * @throws {Error} If any memory not found or memoryIds is empty
305
+ */
306
+ async recordOutcome(memoryIds, runId, outcome, collection) {
307
+ if (memoryIds.length === 0) {
308
+ throw new Error("memoryIds cannot be empty");
309
+ }
310
+ for (const id of memoryIds) {
311
+ const memory = await fetchMemory(id, collection);
312
+ if (!memory) {
313
+ throw new Error("Memory not found");
314
+ }
315
+ const metadata = memory.metadata;
316
+ const outcomeTracking = metadata._outcome_tracking || {
317
+ success: 0,
318
+ failure: 0
319
+ };
320
+ if (outcome === "success") {
321
+ outcomeTracking.success++;
322
+ } else {
323
+ outcomeTracking.failure++;
324
+ }
325
+ const totalOutcomes = outcomeTracking.success + outcomeTracking.failure;
326
+ memory.metadata.votes.success_rate = totalOutcomes > 0 ? outcomeTracking.success / totalOutcomes : 0;
327
+ metadata._outcome_tracking = outcomeTracking;
328
+ await upsertMemory(memory);
329
+ }
330
+ },
331
+ /**
332
+ * Get statistics for memories
333
+ *
334
+ * @param collection - Optional collection filter (omit for all collections)
335
+ * @returns Stats by collection
336
+ */
337
+ async stats(collection) {
338
+ const index = getVectorIndex();
339
+ const collections = collection ? [collection] : await this._listCollections();
340
+ const stats = {};
341
+ for (const col of collections) {
342
+ const memories = await this._fetchAllMemories(col);
343
+ if (memories.length === 0) {
344
+ continue;
345
+ }
346
+ let totalConfidence = 0;
347
+ let totalUpvotes = 0;
348
+ let totalDownvotes = 0;
349
+ let totalCitations = 0;
350
+ let totalSuccessRate = 0;
351
+ for (const mem of memories) {
352
+ const confidence = calculateConfidence(mem);
353
+ totalConfidence += confidence;
354
+ totalUpvotes += mem.metadata.votes.upvotes;
355
+ totalDownvotes += mem.metadata.votes.downvotes;
356
+ totalCitations += mem.metadata.votes.citations;
357
+ totalSuccessRate += mem.metadata.votes.success_rate;
358
+ }
359
+ stats[col] = {
360
+ count: memories.length,
361
+ avg_confidence: totalConfidence / memories.length,
362
+ total_upvotes: totalUpvotes,
363
+ total_downvotes: totalDownvotes,
364
+ total_citations: totalCitations,
365
+ avg_success_rate: totalSuccessRate / memories.length
366
+ };
367
+ }
368
+ return stats;
369
+ },
370
+ /**
371
+ * Prune low-quality memories
372
+ *
373
+ * Removes memories that meet ANY of the following criteria:
374
+ * - Below min_confidence AND older than min_age_days
375
+ * - Exceeds max_downvotes (regardless of age)
376
+ *
377
+ * @param options - Pruning options
378
+ * @returns Result with count and IDs of deleted memories
379
+ */
380
+ async prune(options = {}) {
381
+ const {
382
+ collection,
383
+ min_confidence = 0.1,
384
+ min_age_days = 30,
385
+ max_downvotes
386
+ } = options;
387
+ const collections = collection ? [collection] : await this._listCollections();
388
+ const deletedIds = [];
389
+ for (const col of collections) {
390
+ const memories = await this._fetchAllMemories(col);
391
+ for (const memory of memories) {
392
+ let shouldDelete = false;
393
+ if (max_downvotes !== void 0 && memory.metadata.votes.downvotes > max_downvotes) {
394
+ shouldDelete = true;
395
+ }
396
+ if (!shouldDelete) {
397
+ const confidence = calculateConfidence(memory);
398
+ const createdAt = new Date(memory.metadata.created_at);
399
+ const lastValidatedAt = memory.metadata.last_validated_at ? new Date(memory.metadata.last_validated_at) : void 0;
400
+ const referenceDate = lastValidatedAt || createdAt;
401
+ const ageDays = (Date.now() - referenceDate.getTime()) / (24 * 60 * 60 * 1e3);
402
+ if (confidence < min_confidence && ageDays >= min_age_days) {
403
+ shouldDelete = true;
404
+ }
405
+ }
406
+ if (shouldDelete) {
407
+ await deleteMemory(memory.id, col);
408
+ deletedIds.push(memory.id);
409
+ }
410
+ }
411
+ }
412
+ return {
413
+ deleted_count: deletedIds.length,
414
+ deleted_ids: deletedIds
415
+ };
416
+ },
417
+ /**
418
+ * Internal: List all collections (namespaces) in the index
419
+ *
420
+ * Note: Upstash Vector doesn't provide a native way to list namespaces.
421
+ * This is a workaround that tries common collections and sees which ones have data.
422
+ *
423
+ * @returns Array of collection names
424
+ * @private
425
+ */
426
+ async _listCollections() {
427
+ const commonCollections = [
428
+ "default",
429
+ "agent",
430
+ "human",
431
+ "system",
432
+ "test",
433
+ "other"
434
+ ];
435
+ const collectionsWithData = [];
436
+ for (const col of commonCollections) {
437
+ const memories = await this._fetchAllMemories(col);
438
+ if (memories.length > 0) {
439
+ collectionsWithData.push(col);
440
+ }
441
+ }
442
+ return collectionsWithData;
443
+ },
444
+ /**
445
+ * Internal: Fetch all memories from a collection
446
+ *
447
+ * Uses a broad query to retrieve all memories in a namespace.
448
+ * This is inefficient but necessary given Upstash Vector's API limitations.
449
+ *
450
+ * @param collection - Collection to fetch from
451
+ * @returns Array of memories
452
+ * @private
453
+ */
454
+ async _fetchAllMemories(collection) {
455
+ const index = getVectorIndex();
456
+ const results = await index.query(
457
+ {
458
+ data: "",
459
+ // Empty query to match all
460
+ topK: 1e4,
461
+ includeMetadata: true,
462
+ includeData: true
463
+ },
464
+ { namespace: collection }
465
+ );
466
+ return results.map((result) => ({
467
+ id: String(result.id),
468
+ content: String(result.data),
469
+ metadata: result.metadata
470
+ }));
471
+ }
472
+ };
473
+
474
+ export {
475
+ calculateConfidence,
476
+ upsertMemory,
477
+ queryMemories,
478
+ fetchMemory,
479
+ MemoryService,
480
+ VotingService
481
+ };
482
+ //# sourceMappingURL=chunk-MLNDSBZ4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../memory/src/decay.ts","../../memory/src/client.ts","../../memory/src/memory.ts","../../memory/src/voting.ts"],"sourcesContent":["import type { Memory } from './schemas'\n\n/**\n * Half-life for memory decay in days\n */\nexport const DECAY_HALF_LIFE_DAYS = 30\n\n/**\n * Calculate exponential decay based on memory age\n *\n * Uses 30-day half-life: decay = 0.5^(age_days / 30)\n *\n * @param createdAt - When the memory was created\n * @param lastValidatedAt - Optional validation timestamp that resets the decay clock\n * @returns Decay factor between 0 and 1 (1 = brand new, 0.5 = half-life, etc.)\n */\nexport function calculateDecay(\n createdAt: Date,\n lastValidatedAt?: Date\n): number {\n const referenceDate = lastValidatedAt || createdAt\n const ageDays = (Date.now() - referenceDate.getTime()) / (24 * 60 * 60 * 1000)\n return Math.pow(0.5, ageDays / DECAY_HALF_LIFE_DAYS)\n}\n\n/**\n * Calculate confidence score for a memory\n *\n * Combines time-based decay with reputation score from votes and citations.\n * Formula: decay * reputation\n *\n * Reputation calculation:\n * - Vote score: (upvotes - downvotes) / total_votes (30% weight)\n * - Citation score: success_rate when citations > 0, else 0.5 neutral (70% weight)\n * - Reputation weight: scales from 0 to 1 based on total interactions (capped at 10)\n *\n * @param memory - Memory record with metadata and votes\n * @returns Confidence score between 0 and 1\n */\nexport function calculateConfidence(memory: Memory): number {\n const decay = calculateDecay(\n new Date(memory.metadata.created_at),\n memory.metadata.last_validated_at\n ? new Date(memory.metadata.last_validated_at)\n : undefined\n )\n\n const votes = memory.metadata.votes\n\n // Reputation score based on outcomes\n const totalVotes = votes.upvotes + votes.downvotes\n const voteScore =\n totalVotes > 0 ? (votes.upvotes - votes.downvotes) / totalVotes : 0\n\n // Citation success matters most\n const citationScore = votes.citations > 0 ? votes.success_rate : 0.5 // Neutral for uncited\n\n // Combine: decay * weighted(votes, citations)\n const reputationWeight = Math.min(totalVotes + votes.citations, 10) / 10\n const reputation =\n (voteScore * 0.3 + citationScore * 0.7) * reputationWeight +\n (1 - reputationWeight) * 0.5\n\n return decay * reputation\n}\n","import { Index } from '@upstash/vector'\nimport type { Memory, MemoryMetadata } from './schemas'\n\n/**\n * Lazy-initialized Upstash Vector index singleton.\n * Use this pattern to avoid creating connections at import time in serverless environments.\n */\nlet _index: Index | null = null\n\n/**\n * Get or create the Upstash Vector index instance.\n * Uses lazy initialization to defer connection until first use.\n *\n * @throws {Error} If UPSTASH_VECTOR_REST_URL or UPSTASH_VECTOR_REST_TOKEN env vars are missing\n */\nexport function getVectorIndex(): Index {\n if (!_index) {\n const url = process.env.UPSTASH_VECTOR_REST_URL\n const token = process.env.UPSTASH_VECTOR_REST_TOKEN\n\n if (!url) {\n throw new Error(\n 'UPSTASH_VECTOR_REST_URL environment variable is required'\n )\n }\n if (!token) {\n throw new Error(\n 'UPSTASH_VECTOR_REST_TOKEN environment variable is required'\n )\n }\n\n _index = new Index({\n url,\n token,\n })\n }\n\n return _index\n}\n\n/**\n * Upsert a memory into the vector index.\n * Uses Upstash hosted embeddings by passing data string instead of vector.\n *\n * @param memory - The memory to upsert\n * @returns Promise resolving to the upsert result\n */\nexport async function upsertMemory(memory: Memory): Promise<unknown> {\n const index = getVectorIndex()\n return index.upsert(\n {\n id: memory.id,\n data: memory.content, // Upstash generates embedding from data string\n metadata: memory.metadata,\n },\n { namespace: memory.metadata.collection }\n )\n}\n\n/**\n * Options for querying memories\n */\nexport interface QueryMemoriesOptions {\n /** The search query text */\n query: string\n /** Collection (namespace) to search in */\n collection: string\n /** Number of results to return */\n topK?: number\n /** Metadata filter expression */\n filter?: string\n}\n\n/**\n * Query result with memory metadata\n */\nexport interface QueryMemoryResult {\n id: string\n score: number\n metadata: MemoryMetadata\n}\n\n/**\n * Query memories by semantic similarity.\n *\n * @param options - Query options including search text, collection, topK, and filters\n * @returns Promise resolving to array of query results\n */\nexport async function queryMemories(\n options: QueryMemoriesOptions\n): Promise<QueryMemoryResult[]> {\n const index = getVectorIndex()\n const { query, collection, topK = 10, filter } = options\n\n const results = await index.query(\n {\n data: query, // Upstash generates embedding from query string\n topK,\n includeMetadata: true,\n ...(filter && { filter }),\n },\n { namespace: collection }\n )\n\n return results.map((result) => ({\n id: String(result.id),\n score: result.score,\n metadata: result.metadata as MemoryMetadata,\n }))\n}\n\n/**\n * Delete a memory by ID.\n *\n * @param id - The memory ID to delete\n * @param collection - The collection (namespace) the memory belongs to\n * @returns Promise resolving when deletion is complete\n */\nexport async function deleteMemory(\n id: string,\n collection: string\n): Promise<void> {\n const index = getVectorIndex()\n await index.delete(id, { namespace: collection })\n}\n\n/**\n * Fetch a memory by ID.\n *\n * @param id - The memory ID to fetch\n * @param collection - The collection (namespace) the memory belongs to\n * @returns Promise resolving to the memory or null if not found\n */\nexport async function fetchMemory(\n id: string,\n collection: string\n): Promise<Memory | null> {\n const index = getVectorIndex()\n const results = await index.fetch([id], {\n namespace: collection,\n includeMetadata: true,\n includeData: true,\n })\n\n if (results.length === 0) {\n return null\n }\n\n const result = results[0]\n if (!result) {\n return null\n }\n\n return {\n id: String(result.id),\n content: String(result.data),\n metadata: result.metadata as MemoryMetadata,\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n type QueryMemoriesOptions,\n deleteMemory,\n fetchMemory,\n queryMemories,\n upsertMemory,\n} from './client'\nimport { calculateConfidence } from './decay'\nimport type { Memory, MemoryMetadata, SearchResult } from './schemas'\n\n/**\n * Options for searching memories\n */\nexport interface SearchOptions {\n /** Collection (namespace) to search in */\n collection: string\n /** Number of results to return (default: 10) */\n limit?: number\n /** Minimum similarity score threshold (default: 0.5) */\n threshold?: number\n /** Filter by app slug */\n app_slug?: string\n /** Filter by tags (AND logic) */\n tags?: string[]\n /** Include low-confidence memories (<25%) (default: false) */\n include_stale?: boolean\n}\n\n/**\n * Metadata for storing a new memory\n */\nexport interface StoreMetadata extends Partial<MemoryMetadata> {\n collection: string\n source: 'agent' | 'human' | 'system'\n}\n\n/**\n * Memory Service\n *\n * Provides high-level operations for storing and retrieving memories\n * with semantic search, decay scoring, and metadata filtering.\n */\nexport const MemoryService = {\n /**\n * Store a new memory with embedding generation\n *\n * @param content - The memory content to store\n * @param metadata - Memory metadata (collection and source required)\n * @returns The created memory with generated ID and timestamps\n */\n async store(content: string, metadata: StoreMetadata): Promise<Memory> {\n const now = new Date().toISOString()\n\n const memory: Memory = {\n id: randomUUID(),\n content,\n metadata: {\n collection: metadata.collection,\n source: metadata.source,\n app_slug: metadata.app_slug,\n tags: metadata.tags ?? [],\n confidence: metadata.confidence ?? 1,\n created_at: metadata.created_at ?? now,\n last_validated_at: metadata.last_validated_at,\n votes: metadata.votes ?? {\n upvotes: 0,\n downvotes: 0,\n citations: 0,\n success_rate: 0,\n },\n },\n }\n\n await upsertMemory(memory)\n return memory\n },\n\n /**\n * Find memories by semantic similarity\n *\n * Queries the vector index, fetches full memory data, calculates\n * confidence with time decay, filters by threshold, and sorts by final score.\n *\n * @param query - Search query text\n * @param options - Search options including filters and limits\n * @returns Array of search results with decay-adjusted scores\n */\n async find(query: string, options: SearchOptions): Promise<SearchResult[]> {\n const {\n collection,\n limit = 10,\n threshold = 0.5,\n app_slug,\n tags,\n include_stale = false,\n } = options\n\n // Build metadata filter expression\n let filter: string | undefined\n if (app_slug || tags) {\n const filters: string[] = []\n if (app_slug) {\n filters.push(`app_slug = \"${app_slug}\"`)\n }\n if (tags && tags.length > 0) {\n tags.forEach((tag) => {\n filters.push(`tags[*] = \"${tag}\"`)\n })\n }\n filter = filters.join(' AND ')\n }\n\n // Query vector index\n const queryResults = await queryMemories({\n query,\n collection,\n topK: limit * 2, // Over-fetch to account for filtering\n filter,\n })\n\n // Fetch full memories and calculate confidence scores\n const results: SearchResult[] = []\n\n for (const result of queryResults) {\n const memory = await fetchMemory(result.id, collection)\n if (!memory) continue\n\n // Calculate confidence with time decay\n const confidence = calculateConfidence(memory)\n\n // Filter by confidence threshold (25% for stale)\n if (!include_stale && confidence < 0.25) continue\n\n // Calculate age in days\n const createdAt = new Date(memory.metadata.created_at)\n const lastValidatedAt = memory.metadata.last_validated_at\n ? new Date(memory.metadata.last_validated_at)\n : undefined\n const referenceDate = lastValidatedAt || createdAt\n const ageDays =\n (Date.now() - referenceDate.getTime()) / (24 * 60 * 60 * 1000)\n\n // Calculate decay factor (used in confidence calculation)\n const decayFactor = Math.pow(0.5, ageDays / 30)\n\n // Final score combines similarity with confidence\n const finalScore = result.score * confidence\n\n // Filter by threshold\n if (finalScore < threshold) continue\n\n results.push({\n memory,\n score: finalScore,\n raw_score: result.score,\n age_days: ageDays,\n decay_factor: decayFactor,\n })\n }\n\n // Sort by final score descending\n results.sort((a, b) => b.score - a.score)\n\n // Limit results\n return results.slice(0, limit)\n },\n\n /**\n * Get a specific memory by ID\n *\n * @param id - Memory ID\n * @param collection - Collection the memory belongs to\n * @returns The memory or null if not found\n */\n async get(id: string, collection: string): Promise<Memory | null> {\n return fetchMemory(id, collection)\n },\n\n /**\n * Delete a memory\n *\n * @param id - Memory ID to delete\n * @param collection - Collection the memory belongs to\n */\n async delete(id: string, collection: string): Promise<void> {\n await deleteMemory(id, collection)\n },\n\n /**\n * Validate a memory (resets decay clock)\n *\n * Updates the last_validated_at timestamp to the current time,\n * which resets the time-based decay calculation.\n *\n * @param id - Memory ID to validate\n * @param collection - Collection the memory belongs to\n * @throws {Error} If memory not found\n */\n async validate(id: string, collection: string): Promise<void> {\n const memory = await fetchMemory(id, collection)\n if (!memory) {\n throw new Error('Memory not found')\n }\n\n // Update last_validated_at timestamp\n memory.metadata.last_validated_at = new Date().toISOString()\n\n await upsertMemory(memory)\n },\n}\n","import {\n deleteMemory,\n fetchMemory,\n getVectorIndex,\n upsertMemory,\n} from './client'\nimport { calculateConfidence } from './decay'\nimport type { Memory } from './schemas'\n\n/**\n * Vote type for memory feedback\n */\nexport type VoteType = 'upvote' | 'downvote'\n\n/**\n * Outcome type for citation tracking\n */\nexport type OutcomeType = 'success' | 'failure'\n\n/**\n * Options for pruning memories\n */\nexport interface PruneOptions {\n /** Collection to prune (omit for all collections) */\n collection?: string\n /** Minimum confidence threshold (memories below this are pruned) */\n min_confidence?: number\n /** Minimum age in days before pruning (default: 30) */\n min_age_days?: number\n /** Maximum downvotes before pruning regardless of age (default: none) */\n max_downvotes?: number\n}\n\n/**\n * Result of pruning operation\n */\nexport interface PruneResult {\n /** Number of memories deleted */\n deleted_count: number\n /** IDs of deleted memories */\n deleted_ids: string[]\n}\n\n/**\n * Stats for a collection\n */\nexport interface CollectionStats {\n /** Number of memories in collection */\n count: number\n /** Average confidence score */\n avg_confidence: number\n /** Total upvotes */\n total_upvotes: number\n /** Total downvotes */\n total_downvotes: number\n /** Total citations */\n total_citations: number\n /** Average success rate */\n avg_success_rate: number\n}\n\n/**\n * Stats result by collection\n */\nexport type StatsResult = Record<string, CollectionStats>\n\n/**\n * Internal helper to track outcome counts\n */\ninterface OutcomeTracking {\n success_count: number\n failure_count: number\n}\n\n/**\n * Voting Service\n *\n * Provides operations for voting on memories, tracking citations,\n * recording outcomes, viewing stats, and pruning low-quality memories.\n */\nexport const VotingService = {\n /**\n * Vote on a memory (upvote or downvote)\n *\n * @param id - Memory ID\n * @param collection - Collection the memory belongs to\n * @param voteType - Type of vote ('upvote' or 'downvote')\n * @throws {Error} If memory not found\n */\n async vote(\n id: string,\n collection: string,\n voteType: VoteType\n ): Promise<void> {\n const memory = await fetchMemory(id, collection)\n if (!memory) {\n throw new Error('Memory not found')\n }\n\n // Increment the appropriate vote counter\n if (voteType === 'upvote') {\n memory.metadata.votes.upvotes++\n } else {\n memory.metadata.votes.downvotes++\n }\n\n await upsertMemory(memory)\n },\n\n /**\n * Record a citation (memories were retrieved and used)\n *\n * @param memoryIds - Array of memory IDs\n * @param runId - Run ID for tracking citation context\n * @param collection - Collection the memories belong to\n * @throws {Error} If any memory not found or memoryIds is empty\n */\n async cite(\n memoryIds: string[],\n runId: string,\n collection: string\n ): Promise<void> {\n if (memoryIds.length === 0) {\n throw new Error('memoryIds cannot be empty')\n }\n\n for (const id of memoryIds) {\n const memory = await fetchMemory(id, collection)\n if (!memory) {\n throw new Error('Memory not found')\n }\n\n memory.metadata.votes.citations++\n await upsertMemory(memory)\n }\n },\n\n /**\n * Record outcome for citations (success or failure)\n *\n * Updates the success_rate based on accumulated outcomes.\n * Formula: success_rate = success_count / total_outcomes\n *\n * We store outcome counts in metadata (not in schema yet, but will add).\n * For now, we store them as custom fields in metadata.\n *\n * @param memoryIds - Array of memory IDs\n * @param runId - Run ID for tracking outcome context\n * @param outcome - Outcome type ('success' or 'failure')\n * @param collection - Collection the memories belong to\n * @throws {Error} If any memory not found or memoryIds is empty\n */\n async recordOutcome(\n memoryIds: string[],\n runId: string,\n outcome: OutcomeType,\n collection: string\n ): Promise<void> {\n if (memoryIds.length === 0) {\n throw new Error('memoryIds cannot be empty')\n }\n\n for (const id of memoryIds) {\n const memory = await fetchMemory(id, collection)\n if (!memory) {\n throw new Error('Memory not found')\n }\n\n // Store outcome counts in metadata (extend the type at runtime)\n const metadata = memory.metadata as any\n const outcomeTracking = metadata._outcome_tracking || {\n success: 0,\n failure: 0,\n }\n\n // Update counts based on new outcome\n if (outcome === 'success') {\n outcomeTracking.success++\n } else {\n outcomeTracking.failure++\n }\n\n // Calculate new success rate\n const totalOutcomes = outcomeTracking.success + outcomeTracking.failure\n memory.metadata.votes.success_rate =\n totalOutcomes > 0 ? outcomeTracking.success / totalOutcomes : 0\n\n // Store updated tracking\n metadata._outcome_tracking = outcomeTracking\n\n await upsertMemory(memory)\n }\n },\n\n /**\n * Get statistics for memories\n *\n * @param collection - Optional collection filter (omit for all collections)\n * @returns Stats by collection\n */\n async stats(collection?: string): Promise<StatsResult> {\n const index = getVectorIndex()\n\n // Upstash Vector doesn't provide a direct way to list all namespaces/collections\n // or count all memories across collections. We'll need to implement this by\n // scanning the index. For now, we'll implement a simplified version that\n // requires fetching memories.\n\n // Note: This is a simplified implementation. In production, you might want\n // to maintain stats in a separate data store for efficiency.\n\n const collections = collection\n ? [collection]\n : await this._listCollections()\n const stats: StatsResult = {}\n\n for (const col of collections) {\n // Fetch all memories in this collection\n // This is inefficient but necessary given Upstash Vector's API\n const memories = await this._fetchAllMemories(col)\n\n if (memories.length === 0) {\n continue\n }\n\n // Calculate stats\n let totalConfidence = 0\n let totalUpvotes = 0\n let totalDownvotes = 0\n let totalCitations = 0\n let totalSuccessRate = 0\n\n for (const mem of memories) {\n const confidence = calculateConfidence(mem)\n totalConfidence += confidence\n totalUpvotes += mem.metadata.votes.upvotes\n totalDownvotes += mem.metadata.votes.downvotes\n totalCitations += mem.metadata.votes.citations\n totalSuccessRate += mem.metadata.votes.success_rate\n }\n\n stats[col] = {\n count: memories.length,\n avg_confidence: totalConfidence / memories.length,\n total_upvotes: totalUpvotes,\n total_downvotes: totalDownvotes,\n total_citations: totalCitations,\n avg_success_rate: totalSuccessRate / memories.length,\n }\n }\n\n return stats\n },\n\n /**\n * Prune low-quality memories\n *\n * Removes memories that meet ANY of the following criteria:\n * - Below min_confidence AND older than min_age_days\n * - Exceeds max_downvotes (regardless of age)\n *\n * @param options - Pruning options\n * @returns Result with count and IDs of deleted memories\n */\n async prune(options: PruneOptions = {}): Promise<PruneResult> {\n const {\n collection,\n min_confidence = 0.1,\n min_age_days = 30,\n max_downvotes,\n } = options\n\n const collections = collection\n ? [collection]\n : await this._listCollections()\n const deletedIds: string[] = []\n\n for (const col of collections) {\n const memories = await this._fetchAllMemories(col)\n\n for (const memory of memories) {\n let shouldDelete = false\n\n // Check downvotes threshold (regardless of age)\n if (\n max_downvotes !== undefined &&\n memory.metadata.votes.downvotes > max_downvotes\n ) {\n shouldDelete = true\n }\n\n // Check confidence + age threshold\n if (!shouldDelete) {\n const confidence = calculateConfidence(memory)\n const createdAt = new Date(memory.metadata.created_at)\n const lastValidatedAt = memory.metadata.last_validated_at\n ? new Date(memory.metadata.last_validated_at)\n : undefined\n const referenceDate = lastValidatedAt || createdAt\n const ageDays =\n (Date.now() - referenceDate.getTime()) / (24 * 60 * 60 * 1000)\n\n if (confidence < min_confidence && ageDays >= min_age_days) {\n shouldDelete = true\n }\n }\n\n if (shouldDelete) {\n await deleteMemory(memory.id, col)\n deletedIds.push(memory.id)\n }\n }\n }\n\n return {\n deleted_count: deletedIds.length,\n deleted_ids: deletedIds,\n }\n },\n\n /**\n * Internal: List all collections (namespaces) in the index\n *\n * Note: Upstash Vector doesn't provide a native way to list namespaces.\n * This is a workaround that tries common collections and sees which ones have data.\n *\n * @returns Array of collection names\n * @private\n */\n async _listCollections(): Promise<string[]> {\n // Try common collections and filter to ones that have data\n const commonCollections = [\n 'default',\n 'agent',\n 'human',\n 'system',\n 'test',\n 'other',\n ]\n const collectionsWithData: string[] = []\n\n for (const col of commonCollections) {\n const memories = await this._fetchAllMemories(col)\n if (memories.length > 0) {\n collectionsWithData.push(col)\n }\n }\n\n return collectionsWithData\n },\n\n /**\n * Internal: Fetch all memories from a collection\n *\n * Uses a broad query to retrieve all memories in a namespace.\n * This is inefficient but necessary given Upstash Vector's API limitations.\n *\n * @param collection - Collection to fetch from\n * @returns Array of memories\n * @private\n */\n async _fetchAllMemories(collection: string): Promise<Memory[]> {\n const index = getVectorIndex()\n\n // Query with a broad query to get all memories\n // We use topK=10000 as a practical limit\n const results = await index.query(\n {\n data: '', // Empty query to match all\n topK: 10000,\n includeMetadata: true,\n includeData: true,\n },\n { namespace: collection }\n )\n\n return results.map((result) => ({\n id: String(result.id),\n content: String(result.data),\n metadata: result.metadata as Memory['metadata'],\n }))\n },\n}\n"],"mappings":";;;;;;;;AAAA;AAKO,IAAM,uBAAuB;AAW7B,SAAS,eACd,WACA,iBACQ;AACR,QAAM,gBAAgB,mBAAmB;AACzC,QAAM,WAAW,KAAK,IAAI,IAAI,cAAc,QAAQ,MAAM,KAAK,KAAK,KAAK;AACzE,SAAO,KAAK,IAAI,KAAK,UAAU,oBAAoB;AACrD;AAgBO,SAAS,oBAAoB,QAAwB;AAC1D,QAAM,QAAQ;AAAA,IACZ,IAAI,KAAK,OAAO,SAAS,UAAU;AAAA,IACnC,OAAO,SAAS,oBACZ,IAAI,KAAK,OAAO,SAAS,iBAAiB,IAC1C;AAAA,EACN;AAEA,QAAM,QAAQ,OAAO,SAAS;AAG9B,QAAM,aAAa,MAAM,UAAU,MAAM;AACzC,QAAM,YACJ,aAAa,KAAK,MAAM,UAAU,MAAM,aAAa,aAAa;AAGpE,QAAM,gBAAgB,MAAM,YAAY,IAAI,MAAM,eAAe;AAGjE,QAAM,mBAAmB,KAAK,IAAI,aAAa,MA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