agentlang 0.9.5 → 0.9.7

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 (122) hide show
  1. package/out/cli/main.d.ts.map +1 -1
  2. package/out/cli/main.js +8 -3
  3. package/out/cli/main.js.map +1 -1
  4. package/out/language/generated/ast.d.ts +80 -3
  5. package/out/language/generated/ast.d.ts.map +1 -1
  6. package/out/language/generated/ast.js +62 -0
  7. package/out/language/generated/ast.js.map +1 -1
  8. package/out/language/generated/grammar.d.ts.map +1 -1
  9. package/out/language/generated/grammar.js +432 -218
  10. package/out/language/generated/grammar.js.map +1 -1
  11. package/out/language/main.cjs +485 -218
  12. package/out/language/main.cjs.map +2 -2
  13. package/out/language/parser.js +8 -8
  14. package/out/language/parser.js.map +1 -1
  15. package/out/runtime/agents/common.d.ts +7 -1
  16. package/out/runtime/agents/common.d.ts.map +1 -1
  17. package/out/runtime/agents/common.js +101 -0
  18. package/out/runtime/agents/common.js.map +1 -1
  19. package/out/runtime/agents/impl/anthropic.js +4 -4
  20. package/out/runtime/agents/impl/anthropic.js.map +1 -1
  21. package/out/runtime/agents/impl/openai.js +4 -4
  22. package/out/runtime/agents/impl/openai.js.map +1 -1
  23. package/out/runtime/docs.d.ts.map +1 -1
  24. package/out/runtime/docs.js +109 -7
  25. package/out/runtime/docs.js.map +1 -1
  26. package/out/runtime/embeddings/chunker.d.ts +9 -0
  27. package/out/runtime/embeddings/chunker.d.ts.map +1 -0
  28. package/out/runtime/embeddings/chunker.js +41 -0
  29. package/out/runtime/embeddings/chunker.js.map +1 -0
  30. package/out/runtime/embeddings/index.d.ts +6 -0
  31. package/out/runtime/embeddings/index.d.ts.map +1 -0
  32. package/out/runtime/embeddings/index.js +6 -0
  33. package/out/runtime/embeddings/index.js.map +1 -0
  34. package/out/runtime/embeddings/openai.d.ts +15 -0
  35. package/out/runtime/embeddings/openai.d.ts.map +1 -0
  36. package/out/runtime/embeddings/openai.js +34 -0
  37. package/out/runtime/embeddings/openai.js.map +1 -0
  38. package/out/runtime/embeddings/provider.d.ts +20 -0
  39. package/out/runtime/embeddings/provider.d.ts.map +1 -0
  40. package/out/runtime/embeddings/provider.js +17 -0
  41. package/out/runtime/embeddings/provider.js.map +1 -0
  42. package/out/runtime/embeddings/registry.d.ts +3 -0
  43. package/out/runtime/embeddings/registry.d.ts.map +1 -0
  44. package/out/runtime/embeddings/registry.js +16 -0
  45. package/out/runtime/embeddings/registry.js.map +1 -0
  46. package/out/runtime/exec-graph.d.ts.map +1 -1
  47. package/out/runtime/exec-graph.js +5 -0
  48. package/out/runtime/exec-graph.js.map +1 -1
  49. package/out/runtime/interpreter.d.ts +4 -0
  50. package/out/runtime/interpreter.d.ts.map +1 -1
  51. package/out/runtime/interpreter.js +27 -7
  52. package/out/runtime/interpreter.js.map +1 -1
  53. package/out/runtime/loader.d.ts.map +1 -1
  54. package/out/runtime/loader.js +42 -5
  55. package/out/runtime/loader.js.map +1 -1
  56. package/out/runtime/module.d.ts +22 -4
  57. package/out/runtime/module.d.ts.map +1 -1
  58. package/out/runtime/module.js +76 -10
  59. package/out/runtime/module.js.map +1 -1
  60. package/out/runtime/modules/ai.d.ts +20 -2
  61. package/out/runtime/modules/ai.d.ts.map +1 -1
  62. package/out/runtime/modules/ai.js +333 -37
  63. package/out/runtime/modules/ai.js.map +1 -1
  64. package/out/runtime/modules/auth.d.ts.map +1 -1
  65. package/out/runtime/modules/auth.js +11 -5
  66. package/out/runtime/modules/auth.js.map +1 -1
  67. package/out/runtime/resolvers/interface.d.ts +1 -1
  68. package/out/runtime/resolvers/interface.d.ts.map +1 -1
  69. package/out/runtime/resolvers/interface.js.map +1 -1
  70. package/out/runtime/resolvers/sqldb/database.d.ts +1 -1
  71. package/out/runtime/resolvers/sqldb/database.d.ts.map +1 -1
  72. package/out/runtime/resolvers/sqldb/database.js +139 -50
  73. package/out/runtime/resolvers/sqldb/database.js.map +1 -1
  74. package/out/runtime/resolvers/sqldb/impl.d.ts +22 -2
  75. package/out/runtime/resolvers/sqldb/impl.d.ts.map +1 -1
  76. package/out/runtime/resolvers/sqldb/impl.js +178 -47
  77. package/out/runtime/resolvers/sqldb/impl.js.map +1 -1
  78. package/out/runtime/state.d.ts +1 -0
  79. package/out/runtime/state.d.ts.map +1 -1
  80. package/out/runtime/state.js +3 -0
  81. package/out/runtime/state.js.map +1 -1
  82. package/out/syntaxes/agentlang.monarch.js +1 -1
  83. package/out/syntaxes/agentlang.monarch.js.map +1 -1
  84. package/package.json +188 -185
  85. package/public/pdf.worker.mjs +65152 -0
  86. package/src/cli/main.ts +7 -2
  87. package/src/language/agentlang.langium +8 -2
  88. package/src/language/generated/ast.ts +96 -2
  89. package/src/language/generated/grammar.ts +432 -218
  90. package/src/language/parser.ts +8 -8
  91. package/src/runtime/agents/common.ts +107 -0
  92. package/src/runtime/agents/impl/anthropic.ts +4 -4
  93. package/src/runtime/agents/impl/openai.ts +4 -4
  94. package/src/runtime/docs.ts +120 -9
  95. package/src/runtime/embeddings/chunker.ts +50 -0
  96. package/src/runtime/embeddings/index.ts +5 -0
  97. package/src/runtime/embeddings/openai.ts +49 -0
  98. package/src/runtime/embeddings/provider.ts +37 -0
  99. package/src/runtime/embeddings/registry.ts +17 -0
  100. package/src/runtime/exec-graph.ts +4 -0
  101. package/src/runtime/interpreter.ts +39 -16
  102. package/src/runtime/loader.ts +42 -3
  103. package/src/runtime/module.ts +127 -41
  104. package/src/runtime/modules/ai.ts +467 -38
  105. package/src/runtime/modules/auth.ts +11 -5
  106. package/src/runtime/resolvers/interface.ts +1 -1
  107. package/src/runtime/resolvers/sqldb/database.ts +146 -56
  108. package/src/runtime/resolvers/sqldb/impl.ts +238 -61
  109. package/src/runtime/state.ts +4 -0
  110. package/src/syntaxes/agentlang.monarch.ts +1 -1
  111. package/out/setupClassic.d.ts +0 -98
  112. package/out/setupClassic.d.ts.map +0 -1
  113. package/out/setupClassic.js +0 -38
  114. package/out/setupClassic.js.map +0 -1
  115. package/out/setupCommon.d.ts +0 -2
  116. package/out/setupCommon.d.ts.map +0 -1
  117. package/out/setupCommon.js +0 -33
  118. package/out/setupCommon.js.map +0 -1
  119. package/out/setupExtended.d.ts +0 -40
  120. package/out/setupExtended.d.ts.map +0 -1
  121. package/out/setupExtended.js +0 -67
  122. package/out/setupExtended.js.map +0 -1
@@ -959,9 +959,15 @@ export async function userHasPermissions(
959
959
  }
960
960
  UserRoleCache.set(userId, userRoles);
961
961
  }
962
+ let tempRoles = userRoles;
963
+ const escalatedRole = env.getEscalatedRole();
964
+ if (escalatedRole) {
965
+ tempRoles = userRoles.slice();
966
+ tempRoles.push(escalatedRole);
967
+ }
962
968
  if (
963
- userRoles &&
964
- userRoles.find((role: string) => {
969
+ tempRoles &&
970
+ tempRoles.find((role: string) => {
965
971
  return role === 'admin';
966
972
  })
967
973
  ) {
@@ -973,9 +979,9 @@ export async function userHasPermissions(
973
979
  perms.has(RbacPermissionFlag.UPDATE),
974
980
  perms.has(RbacPermissionFlag.DELETE),
975
981
  ];
976
- if (userRoles !== null) {
977
- for (let i = 0; i < userRoles.length; ++i) {
978
- const permInsts: RbacPermission[] | undefined = RolePermissionsCache.get(userRoles[i]);
982
+ if (tempRoles !== null) {
983
+ for (let i = 0; i < tempRoles.length; ++i) {
984
+ const permInsts: RbacPermission[] | undefined = RolePermissionsCache.get(tempRoles[i]);
979
985
  if (permInsts) {
980
986
  if (
981
987
  permInsts.find((p: RbacPermission) => {
@@ -174,7 +174,7 @@ export class Resolver {
174
174
  entryName: string,
175
175
  moduleName: string,
176
176
  query: string,
177
- options?: Map<string, any>
177
+ options?: any
178
178
  ): Promise<any> {
179
179
  return this.notImpl(`fullTextSearch(${entryName}, ${moduleName}, ${query}, ${options})`);
180
180
  }
@@ -45,6 +45,7 @@ import {
45
45
  import { saveMigration } from '../../modules/core.js';
46
46
  import { getAppSpec } from '../../loader.js';
47
47
  import { WhereClause } from '../interface.js';
48
+ import { AppConfig } from '../../state.js';
48
49
 
49
50
  export let defaultDataSource: DataSource | undefined;
50
51
 
@@ -227,9 +228,10 @@ function makeSqliteDataSource(
227
228
  ): DataSource {
228
229
  const synchronize = needSync();
229
230
  //const runMigrations = isRuntimeMode_migration() || isRuntimeMode_undo_migration() || !synchronize;
230
- return new DataSource({
231
+ const dbPath = config?.dbname || mkDbName();
232
+ const ds = new DataSource({
231
233
  type: 'better-sqlite3',
232
- database: config?.dbname || mkDbName(),
234
+ database: dbPath,
233
235
  synchronize: synchronize,
234
236
  entities: entities,
235
237
  migrationsRun: false,
@@ -239,6 +241,25 @@ function makeSqliteDataSource(
239
241
  undefined: 'ignore',
240
242
  },
241
243
  });
244
+ const originalInit = ds.initialize.bind(ds);
245
+ ds.initialize = async () => {
246
+ const res = await originalInit();
247
+ try {
248
+ const { load } = await import('sqlite-vec');
249
+ const driver = ds.driver as any;
250
+ const db = driver.databaseConnection || driver.nativeDatabase;
251
+ if (db) {
252
+ load(db);
253
+ logger.info('sqlite-vec extension loaded successfully');
254
+ }
255
+ } catch (err: any) {
256
+ logger.warn(
257
+ `Failed to load sqlite-vec extension: ${err.message}. Vector operations may not be available.`
258
+ );
259
+ }
260
+ return res;
261
+ };
262
+ return ds;
242
263
  }
243
264
 
244
265
  async function execMigrationSql(dataSource: DataSource, sql: string[]) {
@@ -323,9 +344,7 @@ function makeSqljsDataSource(
323
344
  });
324
345
  }
325
346
 
326
- const DbType = 'sqlite';
327
-
328
- function getDbType(config?: DatabaseConfig): string {
347
+ function forceGetDbType(config: DatabaseConfig | undefined): string {
329
348
  if (config?.type) return config.type;
330
349
  let envType: string | undefined;
331
350
  try {
@@ -335,6 +354,13 @@ function getDbType(config?: DatabaseConfig): string {
335
354
  } catch {}
336
355
  if (envType) return envType;
337
356
  if (isBrowser()) return 'sqljs';
357
+ return 'sqlite';
358
+ }
359
+
360
+ let DbType: string | undefined;
361
+
362
+ function getDbType(config: DatabaseConfig | undefined): string {
363
+ if (DbType === undefined) DbType = forceGetDbType(config);
338
364
  return DbType;
339
365
  }
340
366
 
@@ -358,16 +384,25 @@ function getDsFunction(
358
384
  }
359
385
 
360
386
  export function isUsingSqlite(): boolean {
361
- return getDbType() == 'sqlite';
387
+ return getDbType(AppConfig?.store) == 'sqlite';
362
388
  }
363
389
 
364
390
  export function isUsingSqljs(): boolean {
365
- return getDbType() == 'sqljs';
391
+ return getDbType(AppConfig?.store) == 'sqljs';
366
392
  }
367
393
 
368
- export function isVectorStoreSupported(): boolean {
369
- // Only Postgres supports pgvector
370
- return getDbType() === 'postgres';
394
+ export async function isVectorStoreSupported(): Promise<boolean> {
395
+ const dbType = getDbType(AppConfig?.store);
396
+ if (dbType === 'postgres') return true;
397
+ if (dbType === 'sqlite') {
398
+ try {
399
+ const sqliteVecModule = await import('sqlite-vec');
400
+ return !!sqliteVecModule;
401
+ } catch {
402
+ return false;
403
+ }
404
+ }
405
+ return false;
371
406
  }
372
407
 
373
408
  export async function initDatabase(config: DatabaseConfig | undefined) {
@@ -403,7 +438,7 @@ export async function initDatabase(config: DatabaseConfig | undefined) {
403
438
  await initVectorStore(vectEnts, DbContext.getGlobalContext());
404
439
  }
405
440
  } else {
406
- throw new Error(`Unsupported database type - ${DbType}`);
441
+ throw new Error(`Unsupported database type - ${getDbType(AppConfig?.store)}`);
407
442
  }
408
443
  }
409
444
  }
@@ -436,49 +471,69 @@ export async function addRowForFullTextSearch(
436
471
  vect: number[],
437
472
  ctx: DbContext
438
473
  ) {
439
- if (!isVectorStoreSupported()) return;
474
+ if (!(await isVectorStoreSupported())) return;
440
475
  try {
441
476
  const vecTableName = tableName + VectorSuffix;
442
477
  const qb = getDatasourceForTransaction(ctx.txnId).createQueryBuilder();
443
478
  const tenantId = await ctx.getTenantId();
444
- const { default: pgvector } = await import('pgvector');
445
- await qb
446
- .insert()
447
- .into(vecTableName)
448
- .values([{ id: id, embedding: pgvector.toSql(vect), __tenant__: tenantId }])
449
- .execute();
479
+ const dbType = getDbType(AppConfig?.store);
480
+ if (dbType === 'postgres') {
481
+ const { default: pgvector } = await import('pgvector');
482
+ await qb
483
+ .insert()
484
+ .into(vecTableName)
485
+ .values([{ id: id, embedding: pgvector.toSql(vect), __tenant__: tenantId }])
486
+ .execute();
487
+ } else {
488
+ await qb
489
+ .insert()
490
+ .into(vecTableName)
491
+ .values([{ id: id, embedding: new Float32Array(vect) }])
492
+ .execute();
493
+ }
450
494
  } catch (err: any) {
451
495
  logger.error(`Failed to add row to vector store - ${err}`);
452
496
  }
453
497
  }
454
498
 
455
499
  export async function initVectorStore(tableNames: string[], ctx: DbContext) {
456
- if (!isVectorStoreSupported()) {
457
- logger.info(`Vector store not supported for ${getDbType()}, skipping init...`);
500
+ if (!(await isVectorStoreSupported())) {
501
+ logger.info(`Vector store not supported for ${getDbType(AppConfig?.store)}, skipping init...`);
458
502
  return;
459
503
  }
504
+ const dbType = getDbType(AppConfig?.store);
460
505
  let notInited = true;
461
- tableNames.forEach(async (vecTableName: string) => {
506
+ for (const vecTableName of tableNames) {
462
507
  const vecRepo = getDatasourceForTransaction(ctx.txnId).getRepository(vecTableName);
463
- if (notInited) {
464
- let failure = false;
465
- try {
466
- await vecRepo.query('CREATE EXTENSION IF NOT EXISTS vector');
467
- } catch (err: any) {
468
- logger.error(`Failed to initialize vector store - ${err}`);
469
- failure = true;
508
+ if (dbType === 'postgres') {
509
+ if (notInited) {
510
+ let failure = false;
511
+ try {
512
+ await vecRepo.query('CREATE EXTENSION IF NOT EXISTS vector');
513
+ } catch (err: any) {
514
+ logger.error(`Failed to initialize vector store - ${err}`);
515
+ failure = true;
516
+ }
517
+ if (failure) continue;
518
+ notInited = false;
470
519
  }
471
- if (failure) return;
472
- notInited = false;
520
+ await vecRepo.query(
521
+ `CREATE TABLE IF NOT EXISTS ${vecTableName} (
522
+ id varchar PRIMARY KEY,
523
+ embedding vector(${DefaultVectorDimension}),
524
+ ${TenantAttributeName} varchar,
525
+ __is_deleted__ boolean default false
526
+ )`
527
+ );
528
+ } else {
529
+ // sqlite-vec - vec0 doesn't support type declarations for metadata columns
530
+ await vecRepo.query(
531
+ `CREATE VIRTUAL TABLE IF NOT EXISTS ${vecTableName} USING vec0(
532
+ id TEXT PRIMARY KEY,
533
+ embedding FLOAT[${DefaultVectorDimension}])`
534
+ );
473
535
  }
474
- await vecRepo.query(
475
- `CREATE TABLE IF NOT EXISTS ${vecTableName} (
476
- id varchar PRIMARY KEY,
477
- embedding vector(${DefaultVectorDimension}),
478
- __is_deleted__ boolean default false
479
- )`
480
- );
481
- });
536
+ }
482
537
  }
483
538
 
484
539
  export async function vectorStoreSearch(
@@ -487,7 +542,7 @@ export async function vectorStoreSearch(
487
542
  limit: number,
488
543
  ctx: DbContext
489
544
  ): Promise<any> {
490
- if (!isVectorStoreSupported()) {
545
+ if (!(await isVectorStoreSupported())) {
491
546
  // Not supported on sqljs/sqlite
492
547
  return [];
493
548
  }
@@ -501,17 +556,31 @@ export async function vectorStoreSearch(
501
556
  }
502
557
  const vecTableName = tableName + VectorSuffix;
503
558
  const qb = getDatasourceForTransaction(ctx.txnId).getRepository(tableName).manager;
504
- const { default: pgvector } = await import('pgvector');
505
- let ownersJoinCond: string = '';
559
+ const dbType = getDbType(AppConfig?.store);
506
560
  const tenantId = await ctx.getTenantId();
561
+ let ownersJoinCond: string = '';
507
562
  if (!hasGlobalPerms) {
508
563
  const ot = ownersTable(tableName);
509
564
  ownersJoinCond = `inner join ${ot} on
510
- ${ot}.path = ${vecTableName}.id and ${ot}.user_id = '${ctx.authInfo.userId}' and ${ot}.r = true
511
- and ${ot}.${TenantAttributeName} = '${tenantId}' and ${vecTableName}.${TenantAttributeName} = '${tenantId}'`;
565
+ ${ot}.path = ${vecTableName}.id and ${ot}.user_id = '${ctx.authInfo.userId}' and ${ot}.r = true
566
+ and ${ot}.${TenantAttributeName} = '${tenantId}'`;
567
+ }
568
+ if (dbType === 'postgres') {
569
+ const { default: pgvector } = await import('pgvector');
570
+ const sql = `select ${vecTableName}.id from ${vecTableName} ${ownersJoinCond} order by embedding <-> $1 LIMIT ${limit}`;
571
+ const args = pgvector.toSql(searchVec);
572
+ return await qb.query(sql, [args]);
573
+ } else {
574
+ // sqlite-vec - join with main table to filter by tenant
575
+ const alias = tableName.toLowerCase();
576
+ const sql = `SELECT ${vecTableName}.id FROM ${vecTableName}
577
+ INNER JOIN ${tableName} ${alias} ON ${alias}.${PathAttributeName} = ${vecTableName}.id
578
+ ${ownersJoinCond}
579
+ WHERE ${alias}.${TenantAttributeName} = '${tenantId}' AND ${alias}.${DeletedFlagAttributeName} = false AND ${vecTableName}.embedding MATCH $1
580
+ LIMIT ${limit}`;
581
+ const args = new Float32Array(searchVec);
582
+ return await qb.query(sql, [args]);
512
583
  }
513
- const sql = `select ${vecTableName}.id from ${vecTableName} ${ownersJoinCond} order by embedding <-> $1 LIMIT ${limit}`;
514
- return await qb.query(sql, [pgvector.toSql(searchVec)]);
515
584
  } catch (err: any) {
516
585
  logger.error(`Vector store search failed - ${err}`);
517
586
  return [];
@@ -523,16 +592,30 @@ export async function vectorStoreSearchEntryExists(
523
592
  id: string,
524
593
  ctx: DbContext
525
594
  ): Promise<boolean> {
526
- if (!isVectorStoreSupported()) return false;
595
+ if (!(await isVectorStoreSupported())) return false;
527
596
  try {
528
597
  const qb = getDatasourceForTransaction(ctx.txnId).getRepository(tableName).manager;
529
598
  const vecTableName = tableName + VectorSuffix;
599
+ const dbType = getDbType(AppConfig?.store);
530
600
  const tenantId = await ctx.getTenantId();
531
- const result: any[] = await qb.query(
532
- `select id from ${vecTableName} where id = $1 abd ${TenantAttributeName} = '${tenantId}'`,
533
- [id]
534
- );
535
- return result !== null && result.length > 0;
601
+
602
+ if (dbType === 'postgres') {
603
+ const result: any[] = await qb.query(
604
+ `select id from ${vecTableName} where id = $1 and ${TenantAttributeName} = '${tenantId}'`,
605
+ [id]
606
+ );
607
+ return result !== null && result.length > 0;
608
+ } else {
609
+ // sqlite-vec - join with main table to verify tenant
610
+ const alias = tableName.toLowerCase();
611
+ const result: any[] = await qb.query(
612
+ `SELECT ${vecTableName}.id FROM ${vecTableName}
613
+ INNER JOIN ${tableName} ${alias} ON ${alias}.${PathAttributeName} = ${vecTableName}.id
614
+ WHERE ${vecTableName}.id = $1 AND ${alias}.${TenantAttributeName} = '${tenantId}'`,
615
+ [id]
616
+ );
617
+ return result !== null && result.length > 0;
618
+ }
536
619
  } catch (err: any) {
537
620
  logger.error(`Vector store search failed - ${err}`);
538
621
  }
@@ -540,15 +623,22 @@ export async function vectorStoreSearchEntryExists(
540
623
  }
541
624
 
542
625
  export async function deleteFullTextSearchEntry(tableName: string, id: string, ctx: DbContext) {
543
- if (!isVectorStoreSupported()) return;
626
+ if (!(await isVectorStoreSupported())) return;
544
627
  try {
545
628
  const qb = getDatasourceForTransaction(ctx.txnId).getRepository(tableName).manager;
546
629
  const vecTableName = tableName + VectorSuffix;
630
+ const dbType = getDbType(AppConfig?.store);
547
631
  const tenantId = await ctx.getTenantId();
548
- await qb.query(
549
- `delete from ${vecTableName} where id = $1 and ${TenantAttributeName} = '${tenantId}'`,
550
- [id]
551
- );
632
+
633
+ if (dbType === 'postgres') {
634
+ await qb.query(
635
+ `delete from ${vecTableName} where id = $1 and ${TenantAttributeName} = '${tenantId}'`,
636
+ [id]
637
+ );
638
+ } else {
639
+ // sqlite-vec - delete just by id (ownership verified by caller)
640
+ await qb.query(`delete from ${vecTableName} where id = $1`, [id]);
641
+ }
552
642
  } catch (err: any) {
553
643
  logger.error(`Vector store delete failed - ${err}`);
554
644
  }