@coasys/ad4m 0.10.0-prerelease → 0.10.0-rc10

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 (40) hide show
  1. package/lib/index.cjs +8167 -683
  2. package/lib/index.js +8167 -684
  3. package/lib/src/Ad4mClient.d.ts +2 -0
  4. package/lib/src/Ad4mClient.js +8 -2
  5. package/lib/src/PubSub.d.ts +1 -0
  6. package/lib/src/PubSub.js +1 -0
  7. package/lib/src/ai/AIClient.d.ts +19 -0
  8. package/lib/src/ai/AIClient.js +236 -0
  9. package/lib/src/ai/AIResolver.d.ts +14 -0
  10. package/lib/src/ai/AIResolver.js +145 -0
  11. package/lib/src/ai/Tasks.d.ts +37 -0
  12. package/lib/src/ai/Tasks.js +165 -0
  13. package/lib/src/buildSchema.js +3 -1
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +13 -1
  16. package/lib/src/index.d.ts +2 -0
  17. package/lib/src/index.js +2 -0
  18. package/lib/src/language/LanguageContext.d.ts +1 -0
  19. package/lib/src/perspectives/PerspectiveProxy.js +84 -60
  20. package/lib/src/runtime/RuntimeClient.d.ts +0 -2
  21. package/lib/src/runtime/RuntimeClient.js +0 -20
  22. package/lib/src/runtime/RuntimeResolver.d.ts +0 -1
  23. package/lib/src/runtime/RuntimeResolver.js +1 -21
  24. package/lib/src/schema.gql +48 -1
  25. package/lib/src/subject/SubjectEntity.js +0 -2
  26. package/lib/src/typeDefs.js +48 -1
  27. package/package.json +7 -3
  28. package/src/Ad4mClient.test.ts +77 -1
  29. package/src/Ad4mClient.ts +7 -0
  30. package/src/PubSub.ts +2 -1
  31. package/src/ai/AIClient.ts +252 -0
  32. package/src/ai/AIResolver.ts +147 -0
  33. package/src/ai/Tasks.ts +121 -0
  34. package/src/buildSchema.ts +3 -1
  35. package/src/expression/ExpressionClient.ts +14 -1
  36. package/src/index.ts +2 -0
  37. package/src/perspectives/PerspectiveProxy.ts +90 -67
  38. package/src/runtime/RuntimeClient.ts +0 -21
  39. package/src/runtime/RuntimeResolver.ts +0 -17
  40. package/src/subject/SubjectEntity.ts +0 -2
@@ -0,0 +1,121 @@
1
+ import { Field, InputType, ObjectType } from "type-graphql";
2
+ import { string } from "yargs";
3
+
4
+ @InputType()
5
+ export class AIPromptExamplesInput {
6
+ @Field()
7
+ input: string;
8
+
9
+ @Field()
10
+ output: string;
11
+
12
+ constructor(input: string, output: string) {
13
+ this.input = input;
14
+ this.output = output;
15
+ }
16
+ }
17
+
18
+
19
+ @ObjectType()
20
+ export class AIPromptExamples {
21
+ @Field()
22
+ input: string;
23
+
24
+ @Field()
25
+ output: string;
26
+
27
+ constructor(input: string, output: string) {
28
+ this.input = input;
29
+ this.output = output;
30
+ }
31
+ }
32
+
33
+ @InputType()
34
+ export class AITaskInput {
35
+ @Field()
36
+ name: string;
37
+
38
+ @Field()
39
+ modelId: string;
40
+
41
+ @Field()
42
+ systemPrompt: string;
43
+
44
+ @Field(type => [AIPromptExamplesInput])
45
+ promptExamples: AIPromptExamplesInput[];
46
+
47
+ @Field(type => String, { nullable: true })
48
+ metaData: string;
49
+
50
+ constructor(name: string, model_id: string, system_prompt: string, prompt_examples: AIPromptExamplesInput[], metaData?: string) {
51
+ this.name = name;
52
+ this.modelId = model_id;
53
+ this.systemPrompt = system_prompt;
54
+ this.promptExamples = prompt_examples;
55
+ this.metaData = metaData;
56
+ }
57
+ }
58
+
59
+ @ObjectType()
60
+ export class AITask {
61
+ @Field()
62
+ name: string;
63
+
64
+ @Field()
65
+ modelId: string;
66
+
67
+ @Field()
68
+ taskId: string;
69
+
70
+ @Field()
71
+ systemPrompt: string;
72
+
73
+ @Field(type => [AIPromptExamples])
74
+ promptExamples: AIPromptExamples[];
75
+
76
+ @Field(type => String, { nullable: true })
77
+ metaData?: string;
78
+
79
+ @Field()
80
+ createdAt: string;
81
+
82
+ @Field()
83
+ updatedAt: string;
84
+
85
+ constructor(name: string, model_id: string, task_id: string, system_prompt: string, prompt_examples: AIPromptExamples[], metaData?: string, created_at?: string, updated_at?: string) {
86
+ this.name = name;
87
+ this.modelId = model_id;
88
+ this.taskId = task_id;
89
+ this.systemPrompt = system_prompt;
90
+ this.promptExamples = prompt_examples;
91
+ this.metaData = metaData;
92
+ this.createdAt = created_at;
93
+ this.updatedAt = updated_at;
94
+ }
95
+ }
96
+
97
+ @ObjectType()
98
+ export class AIModelLoadingStatus {
99
+ @Field()
100
+ model: string;
101
+
102
+ @Field()
103
+ status: string;
104
+
105
+ @Field()
106
+ progress: number;
107
+
108
+ @Field()
109
+ downloaded: boolean;
110
+
111
+ @Field()
112
+ loaded : boolean;
113
+
114
+ constructor(model: string, status: string, progress: number, downloaded: boolean, loaded: boolean) {
115
+ this.model = model;
116
+ this.status = status;
117
+ this.progress = progress;
118
+ this.downloaded = downloaded;
119
+ this.loaded = loaded;
120
+ }
121
+ }
@@ -9,6 +9,7 @@ import LanguageResolver from "./language/LanguageResolver";
9
9
  import NeighbourhoodResolver from "./neighbourhood/NeighbourhoodResolver";
10
10
  import PerspectiveResolver from "./perspectives/PerspectiveResolver";
11
11
  import RuntimeResolver from "./runtime/RuntimeResolver";
12
+ import AIResolver from "./ai/AIResolver";
12
13
 
13
14
  const __filename = fileURLToPath(import.meta.url);
14
15
  const __dirname = path.dirname(__filename);
@@ -20,7 +21,8 @@ buildSchema({
20
21
  LanguageResolver,
21
22
  NeighbourhoodResolver,
22
23
  PerspectiveResolver,
23
- RuntimeResolver
24
+ RuntimeResolver,
25
+ AIResolver
24
26
  ],
25
27
  emitSchemaFile: {
26
28
  path: __dirname + '/schema.gql',
@@ -2,6 +2,7 @@ import { ApolloClient, gql } from "@apollo/client/core";
2
2
  import { InteractionCall, InteractionMeta } from "../language/Language";
3
3
  import unwrapApolloResult from "../unwrapApolloResult";
4
4
  import { ExpressionRendered } from "./Expression";
5
+ import { Literal } from "../Literal";
5
6
 
6
7
  export class ExpressionClient {
7
8
  #apolloClient: ApolloClient<any>
@@ -10,7 +11,19 @@ export class ExpressionClient {
10
11
  this.#apolloClient = client
11
12
  }
12
13
 
13
- async get(url: string): Promise<ExpressionRendered> {
14
+ async get(url: string, alwaysGet: boolean = false): Promise<ExpressionRendered> {
15
+ if(!alwaysGet){
16
+ try {
17
+ let literalValue = Literal.fromUrl(url).get();
18
+ if (typeof literalValue === 'object' && literalValue !== null) {
19
+ if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {
20
+ return literalValue;
21
+ }
22
+ }
23
+ } catch(e) {}
24
+ }
25
+
26
+
14
27
  const { expression } = unwrapApolloResult(await this.#apolloClient.query({
15
28
  query: gql`query expression($url: String!) {
16
29
  expression(url: $url) {
package/src/index.ts CHANGED
@@ -28,3 +28,5 @@ export * from "./DID";
28
28
  export * from "./utils";
29
29
  export * from './subject/SubjectEntity'
30
30
  export * from "./agent/AgentClient";
31
+ export * from "./ai/AIClient"
32
+ export * from "./ai/Tasks"
@@ -365,7 +365,16 @@ export class PerspectiveProxy {
365
365
  */
366
366
  async isSubjectInstance<T>(expression: string, subjectClass: T): Promise<boolean> {
367
367
  let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
368
- return await this.infer(`subject_class("${className}", C), instance(C, "${expression}")`)
368
+ let isInstance = false;
369
+ const maxAttempts = 5;
370
+ let attempts = 0;
371
+
372
+ while (attempts < maxAttempts && !isInstance) {
373
+ isInstance = await this.infer(`subject_class("${className}", C), instance(C, "${expression}")`);
374
+ attempts++;
375
+ }
376
+
377
+ return isInstance
369
378
  }
370
379
 
371
380
 
@@ -432,78 +441,92 @@ export class PerspectiveProxy {
432
441
 
433
442
 
434
443
  private buildQueryFromTemplate(obj: object): string {
435
- // Collect all string properties of the object in a list
436
- let properties = []
437
-
438
- // Collect all collections of the object in a list
439
- let collections = []
440
-
441
- // Collect all string properties of the object in a list
442
- if(Object.getPrototypeOf(obj).__properties) {
443
- Object.keys(Object.getPrototypeOf(obj).__properties).forEach(p => properties.push(p))
444
- } else {
445
- properties.push(...Object.keys(obj).filter(key => !Array.isArray(obj[key])))
446
- }
447
-
448
- // Collect all collections of the object in a list
449
- if (Object.getPrototypeOf(obj).__collections) {
450
- Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c => !collections.includes(c) ?? collections.push(c))
451
- } else {
452
- collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'))
453
- }
454
-
455
- // Collect all set functions of the object in a list
456
- let setFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection"))
457
- // Add all set functions of the object's prototype to that list
458
- setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection")))
459
-
460
- // Collect all add functions of the object in a list
461
- let addFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("add"))
462
- // Add all add functions of the object's prototype to that list
463
- addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("add")))
464
-
465
- // Collect all remove functions of the object in a list
466
- let removeFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("remove"))
467
- // Add all remove functions of the object's prototype to that list
468
- removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("remove")))
469
-
470
- // Collect all add functions of the object in a list
471
- let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("setCollection"))
472
- // Add all add functions of the object's prototype to that list
473
- setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => (typeof obj[key] === "function") && key.startsWith("setCollection")))
474
-
475
- // Construct query to find all subject classes that have the given properties and collections
476
- let query = `subject_class(Class, C)`
477
-
478
- for(let property of properties) {
479
- query += `, property(C, "${property}")`
480
- }
481
- for(let collection of collections) {
482
- query += `, collection(C, "${collection}")`
483
- }
444
+ let result
445
+ // We need to avoid strict mode for the following intropsective code
446
+ (function(obj) {
447
+ // Collect all string properties of the object in a list
448
+ let properties = []
449
+
450
+ // Collect all collections of the object in a list
451
+ let collections = []
452
+
453
+ // Collect all string properties of the object in a list
454
+ if(Object.getPrototypeOf(obj).__properties) {
455
+ Object.keys(Object.getPrototypeOf(obj).__properties).forEach(p => properties.push(p))
456
+ } else {
457
+ properties.push(...Object.keys(obj).filter(key => !Array.isArray(obj[key])))
458
+ }
484
459
 
485
- for(let setFunction of setFunctions) {
486
- // e.g. "setState" -> "state"
487
- let property = setFunction.substring(3)
488
- property = property.charAt(0).toLowerCase() + property.slice(1)
489
- query += `, property_setter(C, "${property}", _)`
490
- }
491
- for(let addFunction of addFunctions) {
492
- query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`
493
- }
460
+ // Collect all collections of the object in a list
461
+ if (Object.getPrototypeOf(obj).__collections) {
462
+ Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c => !collections.includes(c) ?? collections.push(c))
463
+ } else {
464
+ collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'))
465
+ }
494
466
 
495
- for(let removeFunction of removeFunctions) {
496
- query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`
497
- }
467
+ // Collect all set functions of the object in a list
468
+ let setFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection"))
469
+ // Add all set functions of the object's prototype to that list
470
+ setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
471
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
472
+ return descriptor && typeof descriptor.value === "function" && key.startsWith("set") && !key.startsWith("setCollection");
473
+ }));
474
+
475
+ // Collect all add functions of the object in a list
476
+ let addFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("add"))
477
+ // Add all add functions of the object's prototype to that list
478
+ addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
479
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
480
+ return descriptor && typeof descriptor.value === "function" && key.startsWith("add");
481
+ }));
482
+
483
+ // Collect all remove functions of the object in a list
484
+ let removeFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("remove"))
485
+ // Add all remove functions of the object's prototype to that list
486
+ removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
487
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
488
+ return descriptor && typeof descriptor.value === "function" && key.startsWith("remove");
489
+ }));
490
+
491
+ // Collect all add functions of the object in a list
492
+ let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("setCollection"))
493
+ // Add all add functions of the object's prototype to that list
494
+ setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
495
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
496
+ return descriptor && typeof descriptor.value === "function" && key.startsWith("setCollection");
497
+ }));
498
+ // Construct query to find all subject classes that have the given properties and collections
499
+ let query = `subject_class(Class, C)`
500
+
501
+ for(let property of properties) {
502
+ query += `, property(C, "${property}")`
503
+ }
504
+ for(let collection of collections) {
505
+ query += `, collection(C, "${collection}")`
506
+ }
498
507
 
499
- for(let setCollectionFunction of setCollectionFunctions) {
500
- query += `, collection_setter(C, "${collectionSetterToName(setCollectionFunction)}", _)`
501
- }
508
+ for(let setFunction of setFunctions) {
509
+ // e.g. "setState" -> "state"
510
+ let property = setFunction.substring(3)
511
+ property = property.charAt(0).toLowerCase() + property.slice(1)
512
+ query += `, property_setter(C, "${property}", _)`
513
+ }
514
+ for(let addFunction of addFunctions) {
515
+ query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`
516
+ }
502
517
 
518
+ for(let removeFunction of removeFunctions) {
519
+ query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`
520
+ }
503
521
 
504
- query += "."
522
+ for(let setCollectionFunction of setCollectionFunctions) {
523
+ query += `, collection_setter(C, "${collectionSetterToName(setCollectionFunction)}", _)`
524
+ }
505
525
 
506
- return query;
526
+ query += "."
527
+ result = query
528
+ }(obj))
529
+ return result
507
530
  }
508
531
 
509
532
  /** Returns all subject classes that match the given template object.
@@ -57,13 +57,11 @@ export class RuntimeClient {
57
57
  this.#messageReceivedCallbacks = []
58
58
  this.#exceptionOccurredCallbacks = []
59
59
  this.#notificationTriggeredCallbacks = []
60
- this.#notificationRequestedCallbacks = []
61
60
 
62
61
  if(subscribe) {
63
62
  this.subscribeMessageReceived()
64
63
  this.subscribeExceptionOccurred()
65
64
  this.subscribeNotificationTriggered()
66
- this.subscribeNotificationRequested()
67
65
  }
68
66
  }
69
67
 
@@ -323,10 +321,6 @@ export class RuntimeClient {
323
321
  this.#notificationTriggeredCallbacks.push(cb)
324
322
  }
325
323
 
326
- addNotificationRequestedCallback(cb: NotificationRequestedCallback) {
327
- this.#notificationRequestedCallbacks.push(cb)
328
- }
329
-
330
324
  subscribeNotificationTriggered() {
331
325
  this.#apolloClient.subscribe({
332
326
  query: gql` subscription {
@@ -342,21 +336,6 @@ export class RuntimeClient {
342
336
  })
343
337
  }
344
338
 
345
- subscribeNotificationRequested() {
346
- this.#apolloClient.subscribe({
347
- query: gql` subscription {
348
- runtimeNotificationRequested { ${NOTIFICATION_FIELDS} }
349
- }
350
- `}).subscribe({
351
- next: result => {
352
- this.#notificationRequestedCallbacks.forEach(cb => {
353
- cb(result.data.runtimeNotificationRequested)
354
- })
355
- },
356
- error: (e) => console.error(e)
357
- })
358
- }
359
-
360
339
  addMessageCallback(cb: MessageCallback) {
361
340
  this.#messageReceivedCallbacks.push(cb)
362
341
  }
@@ -317,23 +317,6 @@ export default class RuntimeResolver {
317
317
  return true
318
318
  }
319
319
 
320
- @Subscription({topics: RUNTIME_NOTIFICATION_REQUESTED_TOPIC, nullable: true})
321
- runtimeNotificationRequested(): Notification {
322
- return {
323
- id: "test-id",
324
- granted: false,
325
- description: "Test description",
326
- appName: "Test app name",
327
- appUrl: "https://example.com",
328
- appIconPath: "https://fluxsocial.io/favicon",
329
- trigger: "triple(X, ad4m://has_type, flux://message)",
330
- perspectiveIds: ["u983ud-jdhh38d"],
331
- webhookUrl: "https://example.com/webhook",
332
- webhookAuth: "test-auth",
333
-
334
- }
335
- }
336
-
337
320
  @Subscription({topics: RUNTIME_NOTIFICATION_TRIGGERED_TOPIC, nullable: true})
338
321
  runtimeNotificationTriggered(): TriggeredNotification {
339
322
  return {
@@ -43,9 +43,7 @@ export class SubjectEntity {
43
43
 
44
44
  private async getData(id?: string) {
45
45
  const tempId = id ?? this.#baseExpression;
46
- console.log("SubjectEntity: getData")
47
46
  let data = await this.#perspective.getSubjectData(this.#subjectClass, tempId)
48
- console.log("SubjectEntity got data:", data)
49
47
  Object.assign(this, data);
50
48
  this.#baseExpression = tempId;
51
49
  return this