@promptev/context-engine 0.0.0 → 0.0.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.
Files changed (58) hide show
  1. package/README.md +93 -5
  2. package/dist/cli.js +1761 -501
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{config-Bt9bUQqU.d.ts → config-CNnASw5X.d.cts} +42 -5
  5. package/dist/{config-Bl9U789m.d.cts → config-CdlSkKgV.d.ts} +42 -5
  6. package/dist/express.cjs +925 -151
  7. package/dist/express.cjs.map +1 -1
  8. package/dist/express.d.cts +11 -4
  9. package/dist/express.d.ts +11 -4
  10. package/dist/express.js +926 -152
  11. package/dist/express.js.map +1 -1
  12. package/dist/fastify.cjs +923 -151
  13. package/dist/fastify.cjs.map +1 -1
  14. package/dist/fastify.d.cts +8 -4
  15. package/dist/fastify.d.ts +8 -4
  16. package/dist/fastify.js +924 -152
  17. package/dist/fastify.js.map +1 -1
  18. package/dist/{governance-BDkcv4qZ.d.cts → governance-D8g6Wyvb.d.cts} +8 -2
  19. package/dist/{governance-XIScatRO.d.ts → governance-XFVgtEdV.d.ts} +8 -2
  20. package/dist/graph/index.cjs +122 -43
  21. package/dist/graph/index.cjs.map +1 -1
  22. package/dist/graph/index.d.cts +5 -3
  23. package/dist/graph/index.d.ts +5 -3
  24. package/dist/graph/index.js +122 -43
  25. package/dist/graph/index.js.map +1 -1
  26. package/dist/hono.cjs +923 -151
  27. package/dist/hono.cjs.map +1 -1
  28. package/dist/hono.d.cts +8 -4
  29. package/dist/hono.d.ts +8 -4
  30. package/dist/hono.js +924 -152
  31. package/dist/hono.js.map +1 -1
  32. package/dist/index.cjs +2186 -910
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +70 -107
  35. package/dist/index.d.ts +70 -107
  36. package/dist/index.js +2186 -908
  37. package/dist/index.js.map +1 -1
  38. package/dist/mcp.cjs +100 -14
  39. package/dist/mcp.cjs.map +1 -1
  40. package/dist/mcp.d.cts +5 -0
  41. package/dist/mcp.d.ts +5 -0
  42. package/dist/mcp.js +100 -14
  43. package/dist/mcp.js.map +1 -1
  44. package/dist/migrations/sql/0003_tools.sql +2 -0
  45. package/dist/migrations/sql/0004_acl_indexes.sql +23 -2
  46. package/dist/{redaction-BmDSWJ7h.d.cts → redaction-BqD_DEUQ.d.cts} +22 -1
  47. package/dist/{redaction-BmDSWJ7h.d.ts → redaction-BqD_DEUQ.d.ts} +22 -1
  48. package/dist/redaction-presidio.d.cts +1 -1
  49. package/dist/redaction-presidio.d.ts +1 -1
  50. package/dist/{router-CrxZ2y_Z.d.ts → router-B_DTkQgU.d.ts} +17 -2
  51. package/dist/{router-OPgSoYAB.d.cts → router-Dsv3fv0R.d.cts} +17 -2
  52. package/dist/storage-DU1JRno5.d.cts +164 -0
  53. package/dist/storage-Dvt2ZxsV.d.ts +164 -0
  54. package/package.json +61 -23
  55. package/src/migrations/sql/0003_tools.sql +2 -0
  56. package/src/migrations/sql/0004_acl_indexes.sql +23 -2
  57. package/dist/embeddings-B-jZ42mk.d.cts +0 -67
  58. package/dist/embeddings-DaSdAZN3.d.ts +0 -67
@@ -1,7 +1,7 @@
1
1
  import { Pool } from 'pg';
2
- import { G as GraphConfig, C as ContextEngineConfig } from '../config-Bl9U789m.cjs';
3
- import { H as Hooks } from '../redaction-BmDSWJ7h.cjs';
4
- import { E as Embedder } from '../embeddings-B-jZ42mk.cjs';
2
+ import { G as GraphConfig, C as ContextEngineConfig } from '../config-CNnASw5X.cjs';
3
+ import { H as Hooks } from '../redaction-BqD_DEUQ.cjs';
4
+ import { E as Embedder, A as AnnTunable } from '../storage-DU1JRno5.cjs';
5
5
  import 'zod';
6
6
 
7
7
  type Neo4jDriver = {
@@ -63,8 +63,10 @@ declare function buildGraphRanked$1(query: string, opts: {
63
63
  graphStore: GraphStore;
64
64
  hooks?: Hooks | null;
65
65
  sourceIds?: string[] | null;
66
+ documentIds?: string[] | null;
66
67
  principals?: string[] | null;
67
68
  maxDepth?: number;
69
+ backend?: Partial<AnnTunable> | null;
68
70
  }): Promise<string[]>;
69
71
 
70
72
  declare function runGraphStage$1(opts: {
@@ -1,7 +1,7 @@
1
1
  import { Pool } from 'pg';
2
- import { G as GraphConfig, C as ContextEngineConfig } from '../config-Bt9bUQqU.js';
3
- import { H as Hooks } from '../redaction-BmDSWJ7h.js';
4
- import { E as Embedder } from '../embeddings-DaSdAZN3.js';
2
+ import { G as GraphConfig, C as ContextEngineConfig } from '../config-CdlSkKgV.js';
3
+ import { H as Hooks } from '../redaction-BqD_DEUQ.js';
4
+ import { E as Embedder, A as AnnTunable } from '../storage-Dvt2ZxsV.js';
5
5
  import 'zod';
6
6
 
7
7
  type Neo4jDriver = {
@@ -63,8 +63,10 @@ declare function buildGraphRanked$1(query: string, opts: {
63
63
  graphStore: GraphStore;
64
64
  hooks?: Hooks | null;
65
65
  sourceIds?: string[] | null;
66
+ documentIds?: string[] | null;
66
67
  principals?: string[] | null;
67
68
  maxDepth?: number;
69
+ backend?: Partial<AnnTunable> | null;
68
70
  }): Promise<string[]>;
69
71
 
70
72
  declare function runGraphStage$1(opts: {
@@ -62,6 +62,8 @@ var init_hooks = __esm({
62
62
  // src/providers/llm.ts
63
63
  var llm_exports = {};
64
64
  __export(llm_exports, {
65
+ CALL_TIMEOUT_MS: () => CALL_TIMEOUT_MS,
66
+ GEMINI_CALL_TIMEOUT_MS: () => GEMINI_CALL_TIMEOUT_MS,
65
67
  LLMClient: () => LLMClient,
66
68
  TIMEOUT_MS: () => TIMEOUT_MS,
67
69
  buildLlmClient: () => buildLlmClient,
@@ -104,7 +106,7 @@ async function loadGeminiChatClient(apiKey) {
104
106
  if (!Ctor) {
105
107
  throw new ExtraMissingError("gemini", specifier, "gemini llm");
106
108
  }
107
- return new Ctor({ apiKey: apiKey ?? null });
109
+ return new Ctor({ apiKey: apiKey ?? null, httpOptions: { timeout: GEMINI_CALL_TIMEOUT_MS } });
108
110
  }
109
111
  async function loadBedrockSdk() {
110
112
  const specifier = "@aws-sdk/client-bedrock-runtime";
@@ -141,11 +143,13 @@ async function callLlm(cfg, opts) {
141
143
  await owned.aclose();
142
144
  }
143
145
  }
144
- var TIMEOUT_MS, ANTHROPIC_VERSION, ANTHROPIC_MAX_TOKENS, OPENAI_FAMILY, LLMClient;
146
+ var CALL_TIMEOUT_MS, TIMEOUT_MS, GEMINI_CALL_TIMEOUT_MS, ANTHROPIC_VERSION, ANTHROPIC_MAX_TOKENS, OPENAI_FAMILY, LLMClient;
145
147
  var init_llm = __esm({
146
148
  "src/providers/llm.ts"() {
147
149
  init_errors();
148
- TIMEOUT_MS = 3e4;
150
+ CALL_TIMEOUT_MS = 24e4;
151
+ TIMEOUT_MS = CALL_TIMEOUT_MS;
152
+ GEMINI_CALL_TIMEOUT_MS = CALL_TIMEOUT_MS;
149
153
  ANTHROPIC_VERSION = "2023-06-01";
150
154
  ANTHROPIC_MAX_TOKENS = 4096;
151
155
  OPENAI_FAMILY = /* @__PURE__ */ new Set(["openai", "azure_openai", "custom"]);
@@ -173,22 +177,30 @@ var init_llm = __esm({
173
177
  await this.aclose();
174
178
  }
175
179
  async call(opts) {
176
- const { system, user, jsonMode = false, images = null } = opts;
180
+ const {
181
+ system,
182
+ user,
183
+ jsonMode = false,
184
+ images = null,
185
+ maxTokens = null,
186
+ thinkingBudget = null,
187
+ temperature = null
188
+ } = opts;
177
189
  if (this.provider === "anthropic") {
178
- return this.callAnthropic(system, user, jsonMode, images);
190
+ return this.callAnthropic(system, user, jsonMode, images, maxTokens, thinkingBudget, temperature);
179
191
  }
180
192
  if (OPENAI_FAMILY.has(this.provider)) {
181
- return this.callOpenAI(system, user, jsonMode, images);
193
+ return this.callOpenAI(system, user, jsonMode, images, maxTokens, temperature);
182
194
  }
183
195
  if (this.provider === "gemini") {
184
- return this.callGemini(system, user, jsonMode, images);
196
+ return this.callGemini(system, user, jsonMode, images, maxTokens, thinkingBudget, temperature);
185
197
  }
186
198
  if (this.provider === "bedrock") {
187
- return this.callBedrock(system, user, jsonMode, images);
199
+ return this.callBedrock(system, user, jsonMode, images, maxTokens, thinkingBudget, temperature);
188
200
  }
189
201
  throw new Error(`unknown llm provider: ${JSON.stringify(this.provider)}`);
190
202
  }
191
- async callAnthropic(system, user, jsonMode, images) {
203
+ async callAnthropic(system, user, jsonMode, images, maxTokens, thinkingBudget = null, temperature = null) {
192
204
  if (!this.fetchImpl) {
193
205
  throw new Error("anthropic llm client has no fetch implementation");
194
206
  }
@@ -209,26 +221,27 @@ Respond with valid JSON only.`;
209
221
  });
210
222
  }
211
223
  content.push({ type: "text", text: user });
212
- const data = await postJson(
213
- this.fetchImpl,
214
- "https://api.anthropic.com/v1/messages",
215
- {
216
- model: this.model,
217
- max_tokens: ANTHROPIC_MAX_TOKENS,
218
- system,
219
- messages: [{ role: "user", content }]
220
- },
221
- {
222
- "x-api-key": this.cfg.apiKey ?? "",
223
- "anthropic-version": ANTHROPIC_VERSION,
224
- "content-type": "application/json"
225
- }
226
- );
224
+ const body = {
225
+ model: this.model,
226
+ max_tokens: maxTokens ?? ANTHROPIC_MAX_TOKENS,
227
+ system,
228
+ messages: [{ role: "user", content }]
229
+ };
230
+ if (thinkingBudget) {
231
+ body.thinking = { type: "enabled", budget_tokens: thinkingBudget };
232
+ } else if (temperature !== null) {
233
+ body.temperature = temperature;
234
+ }
235
+ const data = await postJson(this.fetchImpl, "https://api.anthropic.com/v1/messages", body, {
236
+ "x-api-key": this.cfg.apiKey ?? "",
237
+ "anthropic-version": ANTHROPIC_VERSION,
238
+ "content-type": "application/json"
239
+ });
227
240
  const text = data.content[0].text;
228
241
  const usage = data.usage ?? {};
229
242
  return [text, { input: usage.input_tokens ?? 0, output: usage.output_tokens ?? 0 }];
230
243
  }
231
- async callOpenAI(system, user, jsonMode, images) {
244
+ async callOpenAI(system, user, jsonMode, images, maxTokens, temperature = null) {
232
245
  if (!this.client) {
233
246
  throw new Error("openai-family llm client has no client");
234
247
  }
@@ -249,12 +262,18 @@ Respond with valid JSON only.`;
249
262
  if (jsonMode) {
250
263
  body.response_format = { type: "json_object" };
251
264
  }
265
+ if (maxTokens) {
266
+ body.max_completion_tokens = maxTokens;
267
+ }
268
+ if (temperature !== null) {
269
+ body.temperature = temperature;
270
+ }
252
271
  const resp = await this.client.chat.completions.create(body);
253
272
  const text = resp.choices[0]?.message?.content ?? "";
254
273
  const usage = resp.usage;
255
274
  return [text, { input: usage?.prompt_tokens ?? 0, output: usage?.completion_tokens ?? 0 }];
256
275
  }
257
- async callGemini(system, user, jsonMode, images) {
276
+ async callGemini(system, user, jsonMode, images, maxTokens, thinkingBudget = null, temperature = null) {
258
277
  if (!this.genaiClient) {
259
278
  this.genaiClient = await loadGeminiChatClient(this.cfg.apiKey);
260
279
  }
@@ -263,10 +282,30 @@ Respond with valid JSON only.`;
263
282
  parts.push({ inlineData: { mimeType: "image/png", data: toBase64(img) } });
264
283
  }
265
284
  parts.push({ text: user });
266
- const config = { systemInstruction: system };
285
+ const config = {
286
+ systemInstruction: system,
287
+ // ALWAYS off, and not as a preference. Automatic function calling means
288
+ // the SDK itself EXECUTES a callable it was handed as a tool and loops
289
+ // on the result — up to ten round trips — before returning anything.
290
+ // This package passes declarations only, so today nothing is executable;
291
+ // but that depends on every future caller continuing to do the same, and
292
+ // an application that gates tool execution behind human approval would
293
+ // have that gate bypassed silently, by a library, with the loop already
294
+ // run before it could object.
295
+ automaticFunctionCalling: { disable: true }
296
+ };
267
297
  if (jsonMode) {
268
298
  config.responseMimeType = "application/json";
269
299
  }
300
+ if (maxTokens) {
301
+ config.maxOutputTokens = maxTokens;
302
+ }
303
+ if (temperature !== null) {
304
+ config.temperature = temperature;
305
+ }
306
+ if (thinkingBudget !== null) {
307
+ config.thinkingConfig = { thinkingBudget };
308
+ }
270
309
  const resp = await this.genaiClient.models.generateContent({
271
310
  model: this.model,
272
311
  contents: parts,
@@ -278,7 +317,7 @@ Respond with valid JSON only.`;
278
317
  const outputTokens = usageMeta?.candidatesTokenCount ?? usageMeta?.candidates_token_count ?? 0;
279
318
  return [text, { input: inputTokens || 0, output: outputTokens || 0 }];
280
319
  }
281
- async callBedrock(system, user, jsonMode, images) {
320
+ async callBedrock(system, user, jsonMode, images, maxTokens, thinkingBudget = null, temperature = null) {
282
321
  const { BedrockRuntimeClient, ConverseCommand } = await loadBedrockSdk();
283
322
  if (jsonMode) {
284
323
  system = `${system}
@@ -302,7 +341,21 @@ Respond with valid JSON only.`;
302
341
  new ConverseCommand({
303
342
  modelId: this.model,
304
343
  system: [{ text: system }],
305
- messages: [{ role: "user", content }]
344
+ messages: [{ role: "user", content }],
345
+ ...maxTokens || temperature !== null ? {
346
+ inferenceConfig: {
347
+ ...maxTokens ? { maxTokens } : {},
348
+ ...temperature !== null ? { temperature } : {}
349
+ }
350
+ } : {},
351
+ // Anthropic-style passthrough — Converse forwards it to the model.
352
+ // Zero (the vision transcription contract) sends nothing: thinking
353
+ // is opt-in for the anthropic models bedrock hosts.
354
+ ...thinkingBudget ? {
355
+ additionalModelRequestFields: {
356
+ thinking: { type: "enabled", budget_tokens: thinkingBudget }
357
+ }
358
+ } : {}
306
359
  })
307
360
  );
308
361
  const text = result.output?.message?.content?.[0]?.text ?? "";
@@ -1144,7 +1197,8 @@ var retrieval_exports = {};
1144
1197
  __export(retrieval_exports, {
1145
1198
  buildGraphRanked: () => buildGraphRanked,
1146
1199
  corpusIsAclUniform: () => corpusIsAclUniform,
1147
- shouldUseCommunitySummaries: () => shouldUseCommunitySummaries
1200
+ shouldUseCommunitySummaries: () => shouldUseCommunitySummaries,
1201
+ vectorSeedIds: () => vectorSeedIds
1148
1202
  });
1149
1203
  function vecLiteral(vector) {
1150
1204
  return `[${vector.map((x) => Number(x)).join(",")}]`;
@@ -1170,8 +1224,8 @@ async function deriveQueryEntities(pool, chunkIds, opts) {
1170
1224
  JOIN context_engine_chunks c ON c.id = ce.chunk_id
1171
1225
  WHERE ce.chunk_id = ANY($1::uuid[]) ${SCOPE}
1172
1226
  GROUP BY e.normalized_name, e.name, e.type
1173
- ORDER BY freq DESC LIMIT $4`,
1174
- [chunkIds, opts.sourceIds, opts.principals, ENTITY_LIMIT]
1227
+ ORDER BY freq DESC LIMIT $5`,
1228
+ [chunkIds, opts.sourceIds, opts.documentIds ?? null, opts.principals, ENTITY_LIMIT]
1175
1229
  );
1176
1230
  return result.rows.map((r) => ({
1177
1231
  normalized_name: r.normalized_name,
@@ -1236,8 +1290,8 @@ async function computeCommunityScores(pool, chunkIds, vector, opts) {
1236
1290
  `SELECT ce.chunk_id::text, ce.entity_id::text
1237
1291
  FROM context_engine_chunk_entities ce
1238
1292
  JOIN context_engine_chunks c ON c.id = ce.chunk_id
1239
- WHERE ce.chunk_id = ANY($1::uuid[]) AND ce.entity_id = ANY($4::uuid[]) ${SCOPE}`,
1240
- [chunkIds, opts.sourceIds, opts.principals, Object.keys(entityScore)]
1293
+ WHERE ce.chunk_id = ANY($1::uuid[]) AND ce.entity_id = ANY($5::uuid[]) ${SCOPE}`,
1294
+ [chunkIds, opts.sourceIds, opts.documentIds ?? null, opts.principals, Object.keys(entityScore)]
1241
1295
  );
1242
1296
  const chunkScores = {};
1243
1297
  for (const row of result.rows) {
@@ -1246,13 +1300,29 @@ async function computeCommunityScores(pool, chunkIds, vector, opts) {
1246
1300
  return chunkScores;
1247
1301
  }
1248
1302
  async function vectorSeedIds(pool, vector, opts) {
1249
- const result = await pool.query(
1250
- `SELECT c.id::text FROM context_engine_chunks c
1251
- WHERE c.embedding IS NOT NULL ${SCOPE}
1252
- ORDER BY c.embedding <=> CAST($1 AS vector) LIMIT $4`,
1253
- [vecLiteral(vector), opts.sourceIds, opts.principals, SEED_LIMIT]
1254
- );
1255
- return result.rows.map((r) => String(r.id));
1303
+ const binds = [opts.sourceIds, opts.documentIds ?? null, opts.principals];
1304
+ const scoped = binds.some((v) => v !== null);
1305
+ const client = await pool.connect();
1306
+ try {
1307
+ await client.query("BEGIN");
1308
+ await opts.backend?.tuneAnnScan?.(client, SEED_LIMIT, scoped);
1309
+ const result = await client.query(
1310
+ `SELECT c.id::text FROM context_engine_chunks c
1311
+ WHERE c.embedding IS NOT NULL ${SCOPE}
1312
+ ORDER BY c.embedding <=> CAST($1 AS vector) LIMIT $5`,
1313
+ [vecLiteral(vector), ...binds, SEED_LIMIT]
1314
+ );
1315
+ await client.query("COMMIT");
1316
+ return result.rows.map((r) => String(r.id));
1317
+ } catch (err) {
1318
+ try {
1319
+ await client.query("ROLLBACK");
1320
+ } catch {
1321
+ }
1322
+ throw err;
1323
+ } finally {
1324
+ client.release();
1325
+ }
1256
1326
  }
1257
1327
  async function buildGraphRanked(query, opts) {
1258
1328
  try {
@@ -1261,11 +1331,18 @@ async function buildGraphRanked(query, opts) {
1261
1331
  const vector = vectors[0] ? [...vectors[0]] : null;
1262
1332
  if (!vector) return [];
1263
1333
  const sourceIds = opts.sourceIds ?? null;
1334
+ const documentIds = opts.documentIds ?? null;
1264
1335
  const principals = opts.principals ?? null;
1265
- const seeds = await vectorSeedIds(opts.pool, vector, { sourceIds, principals });
1336
+ const seeds = await vectorSeedIds(opts.pool, vector, {
1337
+ sourceIds,
1338
+ documentIds,
1339
+ principals,
1340
+ backend: opts.backend
1341
+ });
1266
1342
  if (!seeds.length) return [];
1267
1343
  const queryEntities = await deriveQueryEntities(opts.pool, seeds.slice(0, TOP_SEEDS_FOR_ENTITIES), {
1268
1344
  sourceIds,
1345
+ documentIds,
1269
1346
  principals
1270
1347
  });
1271
1348
  const entityNorms = queryEntities.map((e) => String(e.normalized_name));
@@ -1287,6 +1364,7 @@ async function buildGraphRanked(query, opts) {
1287
1364
  const relScores = await computeRelationshipScores(opts.pool, allIds, entityNorms);
1288
1365
  const commScores = await computeCommunityScores(opts.pool, allIds, vector, {
1289
1366
  sourceIds,
1367
+ documentIds,
1290
1368
  principals,
1291
1369
  useSummaries
1292
1370
  });
@@ -1338,7 +1416,8 @@ var init_retrieval = __esm({
1338
1416
  TOP_SEEDS_FOR_ENTITIES = 20;
1339
1417
  SCOPE = `
1340
1418
  AND ($2::text[] IS NULL OR c.source_id = ANY($2::text[]))
1341
- AND ($3::text[] IS NULL OR c.acl IS NULL OR c.acl && $3::text[])
1419
+ AND ($3::uuid[] IS NULL OR c.document_id = ANY($3::uuid[]))
1420
+ AND ($4::text[] IS NULL OR c.acl IS NULL OR c.acl && $4::text[])
1342
1421
  `;
1343
1422
  }
1344
1423
  });