@dxos/assistant-toolkit 0.8.4-main.ae835ea → 0.8.4-main.e8ec1fe

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 (96) hide show
  1. package/dist/lib/browser/index.mjs +891 -595
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +890 -595
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/blueprints/research/research-blueprint.d.ts.map +1 -1
  8. package/dist/types/src/blueprints/websearch/websearch-toolkit.d.ts +1 -0
  9. package/dist/types/src/blueprints/websearch/websearch-toolkit.d.ts.map +1 -1
  10. package/dist/types/src/crud/graph.d.ts.map +1 -0
  11. package/dist/types/src/crud/graph.test.d.ts.map +1 -0
  12. package/dist/types/src/crud/index.d.ts +2 -0
  13. package/dist/types/src/crud/index.d.ts.map +1 -0
  14. package/dist/types/src/functions/agent/prompt.d.ts +3 -5
  15. package/dist/types/src/functions/agent/prompt.d.ts.map +1 -1
  16. package/dist/types/src/functions/discord/fetch-messages.d.ts +1 -1
  17. package/dist/types/src/functions/discord/index.d.ts +1 -1
  18. package/dist/types/src/functions/discord/index.d.ts.map +1 -1
  19. package/dist/types/src/functions/document/index.d.ts +3 -2
  20. package/dist/types/src/functions/document/index.d.ts.map +1 -1
  21. package/dist/types/src/functions/document/read.d.ts +1 -1
  22. package/dist/types/src/functions/document/update.d.ts +1 -1
  23. package/dist/types/src/functions/entity-extraction/entity-extraction.d.ts +2 -2
  24. package/dist/types/src/functions/entity-extraction/entity-extraction.d.ts.map +1 -1
  25. package/dist/types/src/functions/entity-extraction/index.d.ts +2 -2
  26. package/dist/types/src/functions/entity-extraction/index.d.ts.map +1 -1
  27. package/dist/types/src/functions/exa/exa.d.ts +1 -1
  28. package/dist/types/src/functions/exa/mock.d.ts +1 -1
  29. package/dist/types/src/functions/github/fetch-prs.d.ts +1 -1
  30. package/dist/types/src/functions/linear/index.d.ts +1 -1
  31. package/dist/types/src/functions/linear/index.d.ts.map +1 -1
  32. package/dist/types/src/functions/linear/sync-issues.d.ts +1 -1
  33. package/dist/types/src/functions/research/document-create.d.ts +9 -0
  34. package/dist/types/src/functions/research/document-create.d.ts.map +1 -0
  35. package/dist/types/src/functions/research/index.d.ts +8 -6
  36. package/dist/types/src/functions/research/index.d.ts.map +1 -1
  37. package/dist/types/src/functions/research/research.d.ts +4 -3
  38. package/dist/types/src/functions/research/research.d.ts.map +1 -1
  39. package/dist/types/src/functions/research/types.d.ts +2 -380
  40. package/dist/types/src/functions/research/types.d.ts.map +1 -1
  41. package/dist/types/src/functions/tasks/index.d.ts +2 -2
  42. package/dist/types/src/functions/tasks/index.d.ts.map +1 -1
  43. package/dist/types/src/functions/tasks/read.d.ts +1 -1
  44. package/dist/types/src/functions/tasks/update.d.ts +1 -1
  45. package/dist/types/src/index.d.ts +2 -0
  46. package/dist/types/src/index.d.ts.map +1 -1
  47. package/dist/types/src/toolkits/AssistantToolkit.d.ts +17 -0
  48. package/dist/types/src/toolkits/AssistantToolkit.d.ts.map +1 -0
  49. package/dist/types/src/toolkits/AssistantToolkit.test.d.ts +2 -0
  50. package/dist/types/src/toolkits/AssistantToolkit.test.d.ts.map +1 -0
  51. package/dist/types/src/toolkits/SystemToolkit.d.ts +67 -0
  52. package/dist/types/src/toolkits/SystemToolkit.d.ts.map +1 -0
  53. package/dist/types/src/toolkits/index.d.ts +3 -0
  54. package/dist/types/src/toolkits/index.d.ts.map +1 -0
  55. package/dist/types/tsconfig.tsbuildinfo +1 -1
  56. package/package.json +24 -22
  57. package/src/blueprints/design/design-blueprint.test.ts +9 -14
  58. package/src/blueprints/design/design-blueprint.ts +2 -2
  59. package/src/blueprints/discord/discord-blueprint.ts +2 -2
  60. package/src/blueprints/linear/linear-blueprint.ts +2 -2
  61. package/src/blueprints/planning/planning-blueprint.test.ts +11 -16
  62. package/src/blueprints/planning/planning-blueprint.ts +2 -2
  63. package/src/blueprints/research/research-blueprint.ts +23 -15
  64. package/src/blueprints/websearch/websearch-blueprint.ts +2 -2
  65. package/src/{functions/research → crud}/graph.test.ts +2 -2
  66. package/src/crud/index.ts +5 -0
  67. package/src/experimental/feed.test.ts +11 -8
  68. package/src/functions/agent/prompt.ts +25 -12
  69. package/src/functions/discord/fetch-messages.test.ts +5 -6
  70. package/src/functions/discord/fetch-messages.ts +10 -9
  71. package/src/functions/document/index.ts +1 -0
  72. package/src/functions/entity-extraction/entity-extraction.conversations.json +1 -1
  73. package/src/functions/entity-extraction/entity-extraction.test.ts +11 -19
  74. package/src/functions/entity-extraction/entity-extraction.ts +15 -13
  75. package/src/functions/linear/linear.test.ts +13 -16
  76. package/src/functions/linear/sync-issues.ts +7 -7
  77. package/src/functions/research/{create-document.ts → document-create.ts} +32 -26
  78. package/src/functions/research/index.ts +1 -2
  79. package/src/functions/research/{instructions-research.tpl → research-instructions.tpl} +14 -6
  80. package/src/functions/research/research.conversations.json +1 -10714
  81. package/src/functions/research/research.test.ts +87 -148
  82. package/src/functions/research/research.ts +84 -49
  83. package/src/functions/research/types.ts +14 -12
  84. package/src/index.ts +2 -0
  85. package/src/toolkits/AssistantToolkit.conversations.json +1 -0
  86. package/src/toolkits/AssistantToolkit.test.ts +88 -0
  87. package/src/toolkits/AssistantToolkit.ts +47 -0
  88. package/src/toolkits/SystemToolkit.ts +231 -0
  89. package/src/toolkits/index.ts +6 -0
  90. package/dist/types/src/functions/research/create-document.d.ts +0 -7
  91. package/dist/types/src/functions/research/create-document.d.ts.map +0 -1
  92. package/dist/types/src/functions/research/graph.d.ts.map +0 -1
  93. package/dist/types/src/functions/research/graph.test.d.ts.map +0 -1
  94. /package/dist/types/src/{functions/research → crud}/graph.d.ts +0 -0
  95. /package/dist/types/src/{functions/research → crud}/graph.test.d.ts +0 -0
  96. /package/src/{functions/research → crud}/graph.ts +0 -0
@@ -1,14 +1,21 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/blueprints/design/design-blueprint.ts
2
8
  import { ToolId } from "@dxos/ai";
3
9
  import { Blueprint } from "@dxos/blueprints";
4
- import { Obj as Obj9, Ref as Ref6 } from "@dxos/echo";
5
- import { DataType as DataType7 } from "@dxos/schema";
10
+ import { Obj as Obj10, Ref as Ref6 } from "@dxos/echo";
11
+ import { Text as Text2 } from "@dxos/schema";
6
12
  import { trim as trim5 } from "@dxos/util";
7
13
 
8
14
  // src/functions/agent/prompt.ts
9
15
  import * as Array2 from "effect/Array";
10
16
  import * as Effect from "effect/Effect";
11
17
  import * as Function from "effect/Function";
18
+ import * as Match from "effect/Match";
12
19
  import * as Option from "effect/Option";
13
20
  import * as Schema from "effect/Schema";
14
21
  import { AiService, ConsolePrinter, ModelName } from "@dxos/ai";
@@ -34,10 +41,9 @@ var prompt_default = defineFunction({
34
41
  * Input object or data.
35
42
  * References get auto-resolved.
36
43
  */
37
- input: Schema.Record({
38
- key: Schema.String,
39
- value: Schema.Any
40
- })
44
+ input: Schema.Any.pipe(Schema.annotations({
45
+ title: "Input"
46
+ }))
41
47
  }),
42
48
  outputSchema: Schema.Any,
43
49
  handler: Effect.fnUntraced(function* ({ data }) {
@@ -45,22 +51,14 @@ var prompt_default = defineFunction({
45
51
  input: data.input
46
52
  }, {
47
53
  F: __dxlog_file,
48
- L: 39,
54
+ L: 40,
49
55
  S: this,
50
56
  C: (f, a) => f(...a)
51
57
  });
52
- const input = {
53
- ...data.input
54
- };
55
- for (const key of Object.keys(data.input)) {
56
- const value = data.input[key];
57
- if (Ref.isRef(value)) {
58
- const object = yield* DatabaseService.load(value);
59
- input[key] = Obj.toJSON(object);
60
- } else {
61
- input[key] = JSON.stringify(value);
62
- }
63
- }
58
+ const input = yield* Match.value(data.input).pipe(Match.when((value2) => Ref.isRef(value2), Effect.fnUntraced(function* (ref) {
59
+ const object = yield* DatabaseService.load(ref);
60
+ return Obj.toJSON(object);
61
+ })), Match.orElse(() => Effect.succeed(data.input)));
64
62
  yield* DatabaseService.flush({
65
63
  indexes: true
66
64
  });
@@ -71,10 +69,10 @@ var prompt_default = defineFunction({
71
69
  });
72
70
  log.info("starting agent", {
73
71
  prompt: prompt.id,
74
- input: data.input
72
+ input
75
73
  }, {
76
74
  F: __dxlog_file,
77
- L: 57,
75
+ L: 70,
78
76
  S: this,
79
77
  C: (f, a) => f(...a)
80
78
  });
@@ -123,7 +121,7 @@ import * as Schema2 from "effect/Schema";
123
121
  import { Obj as Obj2 } from "@dxos/echo";
124
122
  import { CredentialsService, TracingService as TracingService2, defineFunction as defineFunction2 } from "@dxos/functions";
125
123
  import { log as log2 } from "@dxos/log";
126
- import { DataType } from "@dxos/schema";
124
+ import { Message } from "@dxos/types";
127
125
  var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant-toolkit/src/functions/discord/fetch-messages.ts";
128
126
  var TimeRange = class extends Schema2.String.pipe(Schema2.pattern(/\d+(s|m|h|d)/)).annotations({
129
127
  description: "Time range. 1d - 1 day, 2h - 2 hours, 30m - 30 minutes, 15s - 15 seconds.",
@@ -196,11 +194,11 @@ var fetch_messages_default = defineFunction2({
196
194
  description: "Exclude messages from these usernames."
197
195
  })
198
196
  }),
199
- handler: Effect2.fnUntraced(function* ({ data: { serverId, channelId, after, last, pageSize = 100, limit = DEFAULT_LIMIT, ignoreUsernames = DEFAULT_IGNORE_USERNAMES } }) {
200
- if (!after && !last) {
197
+ handler: Effect2.fnUntraced(function* ({ data: { serverId, channelId, after, last: last2, pageSize = 100, limit = DEFAULT_LIMIT, ignoreUsernames = DEFAULT_IGNORE_USERNAMES } }) {
198
+ if (!after && !last2) {
201
199
  throw new Error("cannot specify both `after` and `last`");
202
200
  }
203
- const afterTs = last ? Date.now() / 1e3 - TimeRange.toSeconds(last) : after ?? DEFAULT_AFTER;
201
+ const afterTs = last2 ? Date.now() / 1e3 - TimeRange.toSeconds(last2) : after ?? DEFAULT_AFTER;
204
202
  const rest = yield* DiscordREST;
205
203
  let channels = [];
206
204
  channels.push(...yield* rest.listGuildChannels(serverId));
@@ -274,7 +272,7 @@ var parseSnowflake = (snowflake) => {
274
272
  const discordEpoch = 1420070400000n;
275
273
  return new Date(Number((BigInt(snowflake) >> 22n) + discordEpoch));
276
274
  };
277
- var makeMessage = (message) => Obj2.make(DataType.Message, {
275
+ var makeMessage = (message) => Obj2.make(Message.Message, {
278
276
  [Obj2.Meta]: {
279
277
  keys: [
280
278
  {
@@ -378,97 +376,375 @@ import * as Predicate from "effect/Predicate";
378
376
  import * as Schema11 from "effect/Schema";
379
377
  import { AiService as AiService3 } from "@dxos/ai";
380
378
  import { AiSession as AiSession3, makeToolExecutionServiceFromFunctions as makeToolExecutionServiceFromFunctions2, makeToolResolverFromFunctions as makeToolResolverFromFunctions2 } from "@dxos/assistant";
381
- import { Filter as Filter2, Obj as Obj6, Ref as Ref3 } from "@dxos/echo";
382
- import { DatabaseService as DatabaseService8, FunctionInvocationService as FunctionInvocationService2, defineFunction as defineFunction9 } from "@dxos/functions";
379
+ import { Filter as Filter2, Obj as Obj7, Ref as Ref3 } from "@dxos/echo";
380
+ import { DatabaseService as DatabaseService8, defineFunction as defineFunction9 } from "@dxos/functions";
381
+ import { FunctionInvocationServiceLayerTest } from "@dxos/functions-runtime/testing";
383
382
  import { log as log5 } from "@dxos/log";
384
- import { DataType as DataType5 } from "@dxos/schema";
383
+ import { LegacyOrganization as LegacyOrganization2, Message as Message2, Organization, Person as Person2 } from "@dxos/types";
385
384
  import { trim as trim4 } from "@dxos/util";
386
385
 
387
- // src/functions/research/create-document.ts
386
+ // src/crud/graph.ts
387
+ import * as Tool from "@effect/ai/Tool";
388
+ import * as Toolkit from "@effect/ai/Toolkit";
389
+ import * as Context from "effect/Context";
388
390
  import * as Effect5 from "effect/Effect";
391
+ import * as Function3 from "effect/Function";
392
+ import * as Option3 from "effect/Option";
389
393
  import * as Schema5 from "effect/Schema";
390
- import { Relation } from "@dxos/echo";
391
- import { DatabaseService as DatabaseService4, TracingService as TracingService3, defineFunction as defineFunction5 } from "@dxos/functions";
392
- import { invariant } from "@dxos/invariant";
393
- import { DXN, ObjectId } from "@dxos/keys";
394
+ import * as SchemaAST from "effect/SchemaAST";
395
+ import { Obj as Obj3 } from "@dxos/echo";
396
+ import { Filter, Query } from "@dxos/echo";
397
+ import { EntityKind, ObjectId, ReferenceAnnotationId, RelationSourceDXNId, RelationSourceId, RelationTargetDXNId, RelationTargetId, create, getEntityKind, getSchemaDXN, getSchemaTypename, getTypeAnnotation, getTypeIdentifierAnnotation } from "@dxos/echo/internal";
398
+ import { isEncodedReference } from "@dxos/echo-protocol";
399
+ import { mapAst } from "@dxos/effect";
400
+ import { ContextQueueService, DatabaseService as DatabaseService4 } from "@dxos/functions";
401
+ import { DXN } from "@dxos/keys";
394
402
  import { log as log3 } from "@dxos/log";
403
+ import { deepMapValues, isNonNullable, trim } from "@dxos/util";
404
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant-toolkit/src/crud/graph.ts";
405
+ var Subgraph = Schema5.Struct({
406
+ /** Objects and relations. */
407
+ objects: Schema5.Array(Schema5.Any)
408
+ });
409
+ var findRelatedSchema = async (db, anchor) => {
410
+ const allSchemas = [
411
+ ...db.graph.schemaRegistry.schemas
412
+ ];
413
+ return allSchemas.filter((schema) => {
414
+ if (getTypeAnnotation(schema)?.kind !== EntityKind.Relation) {
415
+ return false;
416
+ }
417
+ return isSchemaAddressableByDxn(anchor, DXN.parse(getTypeAnnotation(schema).sourceSchema)) || isSchemaAddressableByDxn(anchor, DXN.parse(getTypeAnnotation(schema).targetSchema));
418
+ }).map((schema) => ({
419
+ schema,
420
+ kind: "relation"
421
+ }));
422
+ };
423
+ var isSchemaAddressableByDxn = (schema, dxn) => {
424
+ if (getTypeIdentifierAnnotation(schema) === dxn.toString()) {
425
+ return true;
426
+ }
427
+ const t = dxn.asTypeDXN();
428
+ if (t) {
429
+ return t.type === getSchemaTypename(schema);
430
+ }
431
+ return false;
432
+ };
433
+ var LocalSearchToolkit = Toolkit.make(Tool.make("search_local_search", {
434
+ description: "Search the local database for information using a vector index",
435
+ parameters: {
436
+ query: Schema5.String.annotations({
437
+ description: "The query to search for. Could be a question or a topic or a set of keywords."
438
+ })
439
+ },
440
+ success: Schema5.Unknown,
441
+ failure: Schema5.Never,
442
+ dependencies: [
443
+ DatabaseService4
444
+ ]
445
+ }));
446
+ var LocalSearchHandler = LocalSearchToolkit.toLayer({
447
+ search_local_search: Effect5.fn(function* ({ query }) {
448
+ const { objects } = yield* DatabaseService4.runQuery(Query.select(Filter.text(query, {
449
+ type: "vector"
450
+ })));
451
+ const results = [
452
+ ...objects
453
+ ];
454
+ const option = yield* Effect5.serviceOption(ContextQueueService);
455
+ if (Option3.isSome(option)) {
456
+ const queueObjects = yield* Effect5.promise(() => option.value.queue.queryObjects());
457
+ results.push(...queueObjects);
458
+ }
459
+ return trim`
460
+ <local_context>
461
+ ${JSON.stringify(results, null, 2)}
462
+ </local_context>
463
+ `;
464
+ })
465
+ });
466
+ var GraphWriterSchema = class extends Context.Tag("@dxos/assistant/GraphWriterSchema")() {
467
+ };
468
+ var makeGraphWriterToolkit = ({ schema }) => {
469
+ return Toolkit.make(Tool.make("graph_writer", {
470
+ description: "Write to the local graph database",
471
+ parameters: createExtractionSchema(schema).fields,
472
+ success: Schema5.Unknown,
473
+ failure: Schema5.Never,
474
+ dependencies: [
475
+ DatabaseService4,
476
+ ContextQueueService
477
+ ]
478
+ }).annotateContext(Context.make(GraphWriterSchema, {
479
+ schema
480
+ })));
481
+ };
482
+ var makeGraphWriterHandler = (toolkit, { onAppend } = {}) => {
483
+ const { schema } = Context.get(toolkit.tools.graph_writer.annotations, GraphWriterSchema);
484
+ return toolkit.toLayer({
485
+ graph_writer: Effect5.fn(function* (input) {
486
+ const { db } = yield* DatabaseService4;
487
+ const { queue } = yield* ContextQueueService;
488
+ const data = yield* Effect5.promise(() => sanitizeObjects(schema, input, db, queue));
489
+ yield* Effect5.promise(() => queue.append(data));
490
+ const dxns = data.map((obj) => Obj3.getDXN(obj));
491
+ onAppend?.(dxns);
492
+ return dxns;
493
+ })
494
+ });
495
+ };
496
+ var createExtractionSchema = (types) => {
497
+ return Schema5.Struct({
498
+ ...Object.fromEntries(types.map(preprocessSchema).map((schema, index) => [
499
+ `objects_${getSanitizedSchemaName(types[index])}`,
500
+ Schema5.optional(Schema5.Array(schema)).annotations({
501
+ description: `The objects of type: ${getSchemaDXN(types[index])?.asTypeDXN().type}. ${SchemaAST.getDescriptionAnnotation(types[index].ast).pipe(Option3.getOrElse(() => ""))}`
502
+ })
503
+ ]))
504
+ });
505
+ };
506
+ var getSanitizedSchemaName = (schema) => {
507
+ return getSchemaDXN(schema).asTypeDXN().type.replaceAll(/[^a-zA-Z0-9]+/g, "_");
508
+ };
509
+ var sanitizeObjects = async (types, data, db, queue) => {
510
+ const entries = types.map((type) => data[`objects_${getSanitizedSchemaName(type)}`]?.map((object) => ({
511
+ data: object,
512
+ schema: type
513
+ })) ?? []).flat();
514
+ const idMap = /* @__PURE__ */ new Map();
515
+ const existingIds = /* @__PURE__ */ new Set();
516
+ const enitties = /* @__PURE__ */ new Map();
517
+ const resolveId = (id) => {
518
+ if (ObjectId.isValid(id)) {
519
+ existingIds.add(id);
520
+ return DXN.fromLocalObjectId(id);
521
+ }
522
+ const mappedId = idMap.get(id);
523
+ if (mappedId) {
524
+ return DXN.fromLocalObjectId(mappedId);
525
+ }
526
+ return void 0;
527
+ };
528
+ const res = entries.map((entry) => {
529
+ if (ObjectId.isValid(entry.data.id)) {
530
+ return entry;
531
+ }
532
+ idMap.set(entry.data.id, ObjectId.random());
533
+ entry.data.id = idMap.get(entry.data.id);
534
+ return entry;
535
+ }).map((entry) => {
536
+ const data2 = deepMapValues(entry.data, (value2, recurse) => {
537
+ if (isEncodedReference(value2)) {
538
+ const ref = value2["/"];
539
+ const id = resolveId(ref);
540
+ if (id) {
541
+ return {
542
+ "/": id.toString()
543
+ };
544
+ } else {
545
+ return {
546
+ "/": `search:?q=${encodeURIComponent(ref)}`
547
+ };
548
+ }
549
+ }
550
+ return recurse(value2);
551
+ });
552
+ if (getEntityKind(entry.schema) === "relation") {
553
+ const sourceDxn = resolveId(data2.source);
554
+ if (!sourceDxn) {
555
+ log3.warn("source not found", {
556
+ source: data2.source
557
+ }, {
558
+ F: __dxlog_file3,
559
+ L: 281,
560
+ S: void 0,
561
+ C: (f, a) => f(...a)
562
+ });
563
+ }
564
+ const targetDxn = resolveId(data2.target);
565
+ if (!targetDxn) {
566
+ log3.warn("target not found", {
567
+ target: data2.target
568
+ }, {
569
+ F: __dxlog_file3,
570
+ L: 285,
571
+ S: void 0,
572
+ C: (f, a) => f(...a)
573
+ });
574
+ }
575
+ delete data2.source;
576
+ delete data2.target;
577
+ data2[RelationSourceDXNId] = sourceDxn;
578
+ data2[RelationTargetDXNId] = targetDxn;
579
+ }
580
+ return {
581
+ data: data2,
582
+ schema: entry.schema
583
+ };
584
+ }).filter((object) => !existingIds.has(object.data.id));
585
+ const { objects: dbObjects } = await db.query(Query.select(Filter.ids(...existingIds))).run();
586
+ const queueObjects = await queue?.getObjectsById([
587
+ ...existingIds
588
+ ]) ?? [];
589
+ const objects = [
590
+ ...dbObjects,
591
+ ...queueObjects
592
+ ].filter(isNonNullable);
593
+ log3.info("objects", {
594
+ dbObjects,
595
+ queueObjects,
596
+ existingIds
597
+ }, {
598
+ F: __dxlog_file3,
599
+ L: 306,
600
+ S: void 0,
601
+ C: (f, a) => f(...a)
602
+ });
603
+ const missing = Array.from(existingIds).filter((id) => !objects.some((object) => object.id === id));
604
+ if (missing.length > 0) {
605
+ throw new Error(`Object IDs do not point to existing objects: ${missing.join(", ")}`);
606
+ }
607
+ return res.flatMap(({ data: data2, schema }) => {
608
+ let skip = false;
609
+ if (RelationSourceDXNId in data2) {
610
+ const id = data2[RelationSourceDXNId].asEchoDXN()?.echoId;
611
+ const obj = objects.find((object) => object.id === id) ?? enitties.get(id);
612
+ if (obj) {
613
+ delete data2[RelationSourceDXNId];
614
+ data2[RelationSourceId] = obj;
615
+ } else {
616
+ skip = true;
617
+ }
618
+ }
619
+ if (RelationTargetDXNId in data2) {
620
+ const id = data2[RelationTargetDXNId].asEchoDXN()?.echoId;
621
+ const obj = objects.find((object) => object.id === id) ?? enitties.get(id);
622
+ if (obj) {
623
+ delete data2[RelationTargetDXNId];
624
+ data2[RelationTargetId] = obj;
625
+ } else {
626
+ skip = true;
627
+ }
628
+ }
629
+ if (!skip) {
630
+ const obj = create(schema, data2);
631
+ enitties.set(obj.id, obj);
632
+ return [
633
+ obj
634
+ ];
635
+ }
636
+ return [];
637
+ });
638
+ };
639
+ var SoftRef = Schema5.Struct({
640
+ "/": Schema5.String
641
+ }).annotations({
642
+ description: "Reference to another object."
643
+ });
644
+ var preprocessSchema = (schema) => {
645
+ const isRelationSchema = getEntityKind(schema) === "relation";
646
+ const go = (ast, visited = /* @__PURE__ */ new Set()) => {
647
+ if (visited.has(ast)) {
648
+ return ast;
649
+ }
650
+ visited.add(ast);
651
+ if (SchemaAST.getAnnotation(ast, ReferenceAnnotationId).pipe(Option3.isSome)) {
652
+ return SoftRef.ast;
653
+ }
654
+ return mapAst(ast, (child) => go(child, visited));
655
+ };
656
+ return Schema5.make(mapAst(schema.ast, (ast) => go(ast))).pipe(Schema5.omit("id"), Schema5.extend(Schema5.Struct({
657
+ id: Schema5.String.annotations({
658
+ description: "The id of this object. Come up with a unique id based on your judgement."
659
+ })
660
+ })), isRelationSchema ? Schema5.extend(Schema5.Struct({
661
+ source: Schema5.String.annotations({
662
+ description: "The id of the source object for this relation."
663
+ }),
664
+ target: Schema5.String.annotations({
665
+ description: "The id of the target object for this relation."
666
+ })
667
+ })) : Function3.identity);
668
+ };
669
+
670
+ // src/functions/research/document-create.ts
671
+ import * as Effect6 from "effect/Effect";
672
+ import * as Schema6 from "effect/Schema";
673
+ import { ArtifactId as ArtifactId3 } from "@dxos/assistant";
674
+ import { Obj as Obj4, Relation } from "@dxos/echo";
675
+ import { DatabaseService as DatabaseService5, TracingService as TracingService3, defineFunction as defineFunction5 } from "@dxos/functions";
676
+ import { log as log4 } from "@dxos/log";
395
677
  import { Markdown as Markdown3 } from "@dxos/plugin-markdown/types";
396
- import { DataType as DataType2 } from "@dxos/schema";
397
- import { trim } from "@dxos/util";
398
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant-toolkit/src/functions/research/create-document.ts";
399
- var create_document_default = defineFunction5({
400
- key: "dxos.org/function/research/create-document",
678
+ import { HasSubject } from "@dxos/types";
679
+ import { trim as trim2 } from "@dxos/util";
680
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant-toolkit/src/functions/research/document-create.ts";
681
+ var document_create_default = defineFunction5({
682
+ key: "dxos.org/function/research/document-create",
401
683
  name: "Create research document",
402
684
  description: "Creates a note summarizing the research.",
403
- inputSchema: Schema5.Struct({
404
- name: Schema5.String.annotations({
405
- description: "Name of the note."
685
+ inputSchema: Schema6.Struct({
686
+ subject: ArtifactId3.annotations({
687
+ description: trim2`
688
+ ID of the object (organization, contact, etc.) for which the research was performed.
689
+ `
406
690
  }),
407
- content: Schema5.String.annotations({
408
- description: trim`
691
+ name: Schema6.String.annotations({
692
+ description: "Name of the document."
693
+ }),
694
+ content: Schema6.String.annotations({
695
+ description: trim2`
409
696
  Content of the note.
410
697
  Supports (and are prefered) references to research objects using @ syntax and <object> tags (refer to research blueprint instructions).
411
698
  `
412
- }),
413
- // TODO(dmaretskyi): Use a specialized type for this (e.g., ArtifactId renamed as RefFromLLM).
414
- target: Schema5.String.annotations({
415
- description: trim`
416
- Id of the object (organization, contact, etc.) for which the research was performed.
417
- This must be a ulid.
418
- `
419
699
  })
420
700
  }),
421
- outputSchema: Schema5.Struct({}),
422
- handler: Effect5.fnUntraced(function* ({ data: { target, name, content } }) {
423
- log3.info("Creating research document", {
424
- target,
701
+ outputSchema: Schema6.Struct({
702
+ document: ArtifactId3.annotations({
703
+ description: "DXN of the created document."
704
+ })
705
+ }),
706
+ handler: Effect6.fnUntraced(function* ({ data: { subject, name, content } }) {
707
+ log4.info("Creating research document", {
708
+ subject,
425
709
  name,
426
710
  content
427
711
  }, {
428
- F: __dxlog_file3,
429
- L: 43,
712
+ F: __dxlog_file4,
713
+ L: 42,
430
714
  S: this,
431
715
  C: (f, a) => f(...a)
432
716
  });
433
- yield* DatabaseService4.flush({
717
+ yield* DatabaseService5.flush({
434
718
  indexes: true
435
719
  });
436
720
  yield* TracingService3.emitStatus({
437
721
  message: "Creating research document..."
438
722
  });
439
- invariant(ObjectId.isValid(target), void 0, {
440
- F: __dxlog_file3,
441
- L: 47,
442
- S: this,
443
- A: [
444
- "ObjectId.isValid(target)",
445
- ""
446
- ]
447
- });
448
- const targetObj = yield* DatabaseService4.resolve(DXN.fromLocalObjectId(target));
449
- const doc = yield* DatabaseService4.add(Markdown3.makeDocument({
723
+ const target = yield* DatabaseService5.resolve(ArtifactId3.toDXN(subject));
724
+ const object = yield* DatabaseService5.add(Markdown3.make({
450
725
  name,
451
726
  content
452
727
  }));
453
- yield* DatabaseService4.add(Relation.make(DataType2.HasSubject, {
454
- [Relation.Source]: doc,
455
- [Relation.Target]: targetObj,
728
+ yield* DatabaseService5.add(Relation.make(HasSubject.HasSubject, {
729
+ [Relation.Source]: object,
730
+ [Relation.Target]: target,
456
731
  completedAt: (/* @__PURE__ */ new Date()).toISOString()
457
732
  }));
458
- yield* DatabaseService4.flush({
733
+ yield* DatabaseService5.flush({
459
734
  indexes: true
460
735
  });
461
- log3.info("Created research document", {
462
- target,
463
- name,
464
- content
736
+ log4.info("Created research document", {
737
+ subject,
738
+ object
465
739
  }, {
466
- F: __dxlog_file3,
467
- L: 66,
740
+ F: __dxlog_file4,
741
+ L: 69,
468
742
  S: this,
469
743
  C: (f, a) => f(...a)
470
744
  });
471
- return {};
745
+ return {
746
+ document: Obj4.getDXN(object).toString()
747
+ };
472
748
  })
473
749
  });
474
750
 
@@ -477,36 +753,41 @@ import * as Toolkit2 from "@effect/ai/Toolkit";
477
753
  import * as AnthropicTool from "@effect/ai-anthropic/AnthropicTool";
478
754
  import * as Array6 from "effect/Array";
479
755
  import * as Effect10 from "effect/Effect";
756
+ import * as Function4 from "effect/Function";
480
757
  import * as Layer3 from "effect/Layer";
758
+ import * as Option4 from "effect/Option";
481
759
  import * as Schema10 from "effect/Schema";
760
+ import * as String10 from "effect/String";
482
761
  import { AiService as AiService2, ConsolePrinter as ConsolePrinter2 } from "@dxos/ai";
483
762
  import { AiSession as AiSession2, GenerationObserver as GenerationObserver2, createToolkit as createToolkit2, makeToolExecutionServiceFromFunctions, makeToolResolverFromFunctions } from "@dxos/assistant";
484
- import { Obj as Obj5 } from "@dxos/echo";
485
- import { DatabaseService as DatabaseService7, FunctionInvocationService, TracingService as TracingService4, defineFunction as defineFunction8 } from "@dxos/functions";
486
- import { DataType as DataType4 } from "@dxos/schema";
763
+ import { Template as Template2 } from "@dxos/blueprints";
764
+ import { Obj as Obj6 } from "@dxos/echo";
765
+ import { DatabaseService as DatabaseService7, TracingService as TracingService4, defineFunction as defineFunction8 } from "@dxos/functions";
766
+ import { FunctionInvocationServiceLayerTestMocked } from "@dxos/functions-runtime/testing";
767
+ import { Person } from "@dxos/types";
487
768
  import { trim as trim3 } from "@dxos/util";
488
769
 
489
770
  // src/functions/exa/exa.ts
490
- import * as Effect6 from "effect/Effect";
491
- import * as Schema6 from "effect/Schema";
771
+ import * as Effect7 from "effect/Effect";
772
+ import * as Schema7 from "effect/Schema";
492
773
  import Exa from "exa-js";
493
774
  import { CredentialsService as CredentialsService2, defineFunction as defineFunction6 } from "@dxos/functions";
494
775
  var exa_default = defineFunction6({
495
776
  key: "dxos.org/function/exa",
496
777
  name: "Exa",
497
778
  description: "Search the web for information",
498
- inputSchema: Schema6.Struct({
499
- query: Schema6.String.annotations({
779
+ inputSchema: Schema7.Struct({
780
+ query: Schema7.String.annotations({
500
781
  description: "The query to search for."
501
782
  })
502
783
  }),
503
- outputSchema: Schema6.Unknown,
504
- handler: Effect6.fnUntraced(function* ({ data: { query } }) {
784
+ outputSchema: Schema7.Unknown,
785
+ handler: Effect7.fnUntraced(function* ({ data: { query } }) {
505
786
  const credential = yield* CredentialsService2.getCredential({
506
787
  service: "exa.ai"
507
788
  });
508
789
  const exa = new Exa(credential.apiKey);
509
- const context = yield* Effect6.promise(async () => exa.searchAndContents(query, {
790
+ const context = yield* Effect7.promise(async () => exa.searchAndContents(query, {
510
791
  type: "auto",
511
792
  text: {
512
793
  maxCharacters: 3e3
@@ -518,8 +799,8 @@ var exa_default = defineFunction6({
518
799
  });
519
800
 
520
801
  // src/functions/exa/mock.ts
521
- import * as Effect7 from "effect/Effect";
522
- import * as Schema7 from "effect/Schema";
802
+ import * as Effect8 from "effect/Effect";
803
+ import * as Schema8 from "effect/Schema";
523
804
  import { defineFunction as defineFunction7 } from "@dxos/functions";
524
805
 
525
806
  // src/testing/data/exa-search-1748337321991.ts
@@ -985,390 +1266,103 @@ var exa_search_1748337344119_default = {
985
1266
  id: "https://github.com/RoboZoom/knowledge_management",
986
1267
  title: "GitHub - RoboZoom/knowledge_management",
987
1268
  url: "https://github.com/RoboZoom/knowledge_management",
988
- publishedDate: "2024-02-08T02:20:22.000Z",
989
- author: "RoboZoom",
990
- score: 0.37371376156806946,
991
- text: "\n \n \n \n \n \n \n \n \n \n \nGitHub Copilot\n \nWrite better code with AI\n \n \n \n \n \n \nGitHub Models\n \nNew\n \n \nManage and compare prompts\n \n \n \n \n \n \nGitHub Advanced Security\n \nFind and fix vulnerabilities\n \n \n \n \n \n \nActions\n \nAutomate any workflow\n \n \n \n \n \n \nCodespaces\n \nInstant dev environments\n \n \n \n \n \n \n \n \n \n \nIssues\n \nPlan and track work\n \n \n \n \n \n \nCode Review\n \nManage code changes\n \n \n \n \n \n \nDiscussions\n \nCollaborate outside of code\n \n \n \n \n \n \nCode Search\n \nFind more, search less\n \n \n \n \n \n \n \n \n \n \n Explore \n \n \nLearning Pathways\n \n \n \nEvents &amp; Webinars\n \n \n \nEbooks &amp; Whitepapers\n \n \n \nCustomer Stories\n \n \n \nPartners\n \n \n \nExecutive Insights\n \n \n \n \n \n \n \n \n \n \n \n \nGitHub Sponsors\n \nFund open source developers\n \n \n \n \n \n \n \n \n \n \nThe ReadME Project\n \nGitHub community articles\n \n \n \n \n \n \n \n \n \n \n \n \n \nEnterprise platform\n \nAI-powered developer platform\n \n \n \n \n \n \n Pricing \n \n \n \n \n \nSign up\n \n \n",
992
- image: "https://opengraph.githubassets.com/2388498497e355faeecdd0ebc0ae18ac0680ba329b5f7030aa21bc38ddaa6b8b/RoboZoom/knowledge_management",
993
- favicon: "https://github.com/fluidicon.png"
994
- },
995
- {
996
- id: "https://creati.ai/ai-tools/sciphi/",
997
- title: "SciPhi: Build, Deploy, and Optimize AI Systems | Creati.ai",
998
- url: "https://creati.ai/ai-tools/sciphi/",
999
- publishedDate: "2024-07-01T00:00:00.000Z",
1000
- author: "",
1001
- score: 0.37101393938064575,
1002
- text: "SciPhi simplifies building, deploying, and optimizing Retrieval-Augmented Generation (RAG) systems, empowering developers to focus on AI innovation. Added on: Social &amp; Email: Platform: SciPhi SciPhi simplifies building, deploying, and optimizing Retrieval-Augmented Generation (RAG) systems, empowering developers to focus on AI innovation. Added on: Social &amp; Email: Platform: What is SciPhi? SciPhi is an open-source platform designed to simplify the building, deploying, and scaling of Retrieval-Augmented Generation (RAG) systems. It provides an end-to-end solution for developers, enabling them to focus on AI innovation without worrying about the underlying infrastructure. With tools for automated knowledge graph extraction, document and user management, and robust observability, SciPhi ensures efficient and optimized RAG system deployment. Who will use SciPhi? Developers AI Engineers Data Scientists Tech Startups Research Institutions How to use the SciPhi? Step1: Visit the SciPhi website. Step2: Sign up for an account or log in. Step3: Access the platform's dashboard. Step4: Follow guides to build and deploy your RAG system. Step5: Use tools for knowledge graph extraction and management. Step6: Optimize and monitor your system using provided observability features. SciPhi's Core Features &amp; Benefits The Core Features of SciPhi End-to-End RAG System Deployment Automated Knowledge Graph Extraction Document and User Management Robust Observability Tools The Benefits of SciPhi Simplifies AI Development Speeds Up Deployment Time Enhances System Optimization Reduces Infrastructure Complexity SciPhi's Main Use Cases &amp; Applications Building RAG Systems for AI Applications Deploying Knowledge Graphs Managing Large Document Repositories Optimizing AI System Performance FAQs of SciPhi SciPhi is an open-source platform designed to simplify building, deploying, and optimizing Retrieval-Augmented Generation (RAG) systems. SciPhi is intended for developers, AI engineers, data scientists, tech startups, and research institutions. Core features include end-to-end RAG system deployment, automated knowledge graph extraction, document and user management, and robust observability tools. Visit the SciPhi website, sign up for an account, and follow the guides to build and deploy your RAG system. SciPhi supports web platforms. SciPhi simplifies AI development, speeds up deployment time, enhances system optimization, and reduces infrastructure complexity. Yes, alternatives include LangChain, LlamaIndex, Haystack, and Flower. SciPhi supports building RAG systems for AI applications, deploying knowledge graphs, managing large document repositories, and optimizing AI system performance. You can reach out to their support team via their support email provided on the website. SciPhi offers both free and paid plans. Details on pricing can be found on their website. SciPhi Company Information Website: https://www.sciphi.ai Company Name: SciPhi Support Email: [ema",
1003
- image: "https://cdn-image.creati.ai/ai-tools/product-image/sciphi.webp",
1004
- favicon: "https://cdn-image.creati.ai/image/Creatiai.ico"
1005
- },
1006
- {
1007
- id: "https://helpjuice.com/blog/open-source-knowledge-base",
1008
- title: "The 12 Best Open Source Knowledge Base Software for 2024",
1009
- url: "https://helpjuice.com/blog/open-source-knowledge-base",
1010
- author: "Zeeshan Khan",
1011
- text: "\n \n \n \n \n At Helpjuice / \n \n #Software &amp; Alternatives\n May 15 2025 \n 11m read \n \n \n \n \n On the hunt for the perfect knowledge base software that\u2019s open source? This post will walk you through the best options for your business. \n \n \n \n \n There\u2019s no denying that a knowledge base can make a major impact on your organization.\xA0 Whether it's to help provide better support to your customers or to enable your employees to find the information they need to do their job, a finely-tuned knowledge base can make all the difference when it comes to how knowledge and information flows through your business. And with plenty of options on the market out there, there\u2019s certainly no shortage of open source knowledge base software. But how can you tell you\u2019re not investing time into installing and learning new software that your team won't use anyway? How can you avoid the time and effort put into an open source option that you later determine to not be a good fit for your needs?\xA0 It\u2019s simple\u2014do a little research beforehand. We know, we know\u2014you don\u2019t have endless time to invest in that kind of thing (what with a business to run and all). That\u2019s why we\u2019ve created a helpful list of the must-consider open source knowledge base software that companies of all niches, industries, and sizes should consider.\xA0 We\u2019re even throwing in a little helpful knowledge that should equip you with the information needed to choose the right software for you\u2014like what knowledge base software is in the first place, the benefits of open source software, and how to address your unique needs as a company to choose the right software for you.\xA0 Want to skip ahead on some of the basics of open-source knowledge base software?\xA0 Be our guest.\xA0 The best open source knowledge base software includes: \n BookStack \n OpenKM \n myBase \n eXo \n PHPKB \n Documize \n DocuWiki \n phpMyFAQ \n MediaWiki \n xWiki \n TWiki \n TiddlyWiki \n What is an Open Source Knowledge Base? Before we dive into which open-source knowledge base software you should consider for your business, we should probably ensure we\u2019re on the same page about what exactly open-source knowledge base software is.\xA0 First things first, let\u2019s start with the term knowledge base. A knowledge base is a central place that allows structured storage of information where users can search for and access this information. \xA0Knowledge base software should be the key tool that helps make this process seamless, simplified, and efficient. Knowledge base software is designed to help you create and manage your knowledge base to the best of your ability. this usually includes setting up the knowledge base architecture, creating and editing documentation, searching, and analyzing your knowledge base, and more. Ideally, this is the irreplaceable piece of the puzzle that operates your entire knowledge management system that helps orchestrate, manage, and optimize the flow of knowledge within your organization.\xA0 That part seems pretty clear, right? Next, we\u2019ll move on to",
1012
- image: "https://static.helpjuice.com/helpjuice_production/uploads/upload/image/4752/direct/1636499945090-Open%20Source%20Knowledge%20Base%20Software.jpg",
1013
- favicon: "https://static.helpjuice.com/assets/favicon-32x32-161f2153235b710a8ed7b9233ed6b195936bdb57bf1310e720f7fea79547cf9d.png"
1014
- }
1015
- ],
1016
- costDollars: {
1017
- total: 0.015,
1018
- search: {
1019
- neural: 5e-3
1020
- },
1021
- contents: {
1022
- text: 0.01
1023
- }
1024
- }
1025
- };
1026
-
1027
- // src/testing/data/index.ts
1028
- var SEARCH_RESULTS = [
1029
- exa_search_1748337321991_default,
1030
- exa_search_1748337331526_default,
1031
- exa_search_1748337344119_default
1032
- ];
1033
-
1034
- // src/functions/exa/mock.ts
1035
- var mock_default = defineFunction7({
1036
- key: "dxos.org/function/exa-mock",
1037
- name: "Exa mock",
1038
- description: "Search the web for information",
1039
- inputSchema: Schema7.Struct({
1040
- query: Schema7.String.annotations({
1041
- description: "The query to search for."
1042
- })
1043
- }),
1044
- outputSchema: Schema7.Unknown,
1045
- handler: Effect7.fnUntraced(function* ({ data: { query } }) {
1046
- const result = SEARCH_RESULTS.reduce((closest, current) => {
1047
- if (!current.autopromptString) {
1048
- return closest;
1049
- }
1050
- if (!closest) {
1051
- return current;
1052
- }
1053
- const dist1 = levenshteinDistance(query, current.autopromptString);
1054
- const dist2 = levenshteinDistance(query, closest.autopromptString || "");
1055
- const weight1 = dist1 / Math.max(query.length, current.autopromptString.length);
1056
- const weight2 = dist2 / Math.max(query.length, closest.autopromptString?.length || 0);
1057
- return weight1 < weight2 ? current : closest;
1058
- }, null);
1059
- return result;
1060
- })
1061
- });
1062
- var levenshteinDistance = (str1, str2) => {
1063
- const m = str1.length;
1064
- const n = str2.length;
1065
- const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
1066
- for (let i = 0; i <= m; i++) {
1067
- dp[i][0] = i;
1068
- }
1069
- for (let j = 0; j <= n; j++) {
1070
- dp[0][j] = j;
1071
- }
1072
- for (let i = 1; i <= m; i++) {
1073
- for (let j = 1; j <= n; j++) {
1074
- dp[i][j] = str1[i - 1] === str2[j - 1] ? dp[i - 1][j - 1] : Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1;
1075
- }
1076
- }
1077
- return dp[m][n];
1078
- };
1079
-
1080
- // src/functions/research/graph.ts
1081
- import * as Tool from "@effect/ai/Tool";
1082
- import * as Toolkit from "@effect/ai/Toolkit";
1083
- import * as Context from "effect/Context";
1084
- import * as Effect8 from "effect/Effect";
1085
- import * as Function3 from "effect/Function";
1086
- import * as Option3 from "effect/Option";
1087
- import * as Schema8 from "effect/Schema";
1088
- import * as SchemaAST from "effect/SchemaAST";
1089
- import { Obj as Obj3 } from "@dxos/echo";
1090
- import { Filter, Query } from "@dxos/echo";
1091
- import { EntityKind, ObjectId as ObjectId2, ReferenceAnnotationId, RelationSourceDXNId, RelationSourceId, RelationTargetDXNId, RelationTargetId, create, getEntityKind, getSchemaDXN, getSchemaTypename, getTypeAnnotation, getTypeIdentifierAnnotation } from "@dxos/echo/internal";
1092
- import { isEncodedReference } from "@dxos/echo-protocol";
1093
- import { mapAst } from "@dxos/effect";
1094
- import { ContextQueueService, DatabaseService as DatabaseService5 } from "@dxos/functions";
1095
- import { DXN as DXN2 } from "@dxos/keys";
1096
- import { log as log4 } from "@dxos/log";
1097
- import { deepMapValues, isNonNullable, trim as trim2 } from "@dxos/util";
1098
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant-toolkit/src/functions/research/graph.ts";
1099
- var Subgraph = Schema8.Struct({
1100
- /** Objects and relations. */
1101
- objects: Schema8.Array(Schema8.Any)
1102
- });
1103
- var findRelatedSchema = async (db, anchor) => {
1104
- const allSchemas = [
1105
- ...db.graph.schemaRegistry.schemas
1106
- ];
1107
- return allSchemas.filter((schema) => {
1108
- if (getTypeAnnotation(schema)?.kind !== EntityKind.Relation) {
1109
- return false;
1110
- }
1111
- return isSchemaAddressableByDxn(anchor, DXN2.parse(getTypeAnnotation(schema).sourceSchema)) || isSchemaAddressableByDxn(anchor, DXN2.parse(getTypeAnnotation(schema).targetSchema));
1112
- }).map((schema) => ({
1113
- schema,
1114
- kind: "relation"
1115
- }));
1116
- };
1117
- var isSchemaAddressableByDxn = (schema, dxn) => {
1118
- if (getTypeIdentifierAnnotation(schema) === dxn.toString()) {
1119
- return true;
1120
- }
1121
- const t = dxn.asTypeDXN();
1122
- if (t) {
1123
- return t.type === getSchemaTypename(schema);
1124
- }
1125
- return false;
1126
- };
1127
- var LocalSearchToolkit = Toolkit.make(Tool.make("search_local_search", {
1128
- description: "Search the local database for information using a vector index",
1129
- parameters: {
1130
- query: Schema8.String.annotations({
1131
- description: "The query to search for. Could be a question or a topic or a set of keywords."
1132
- })
1133
- },
1134
- success: Schema8.Unknown,
1135
- failure: Schema8.Never,
1136
- dependencies: [
1137
- DatabaseService5
1138
- ]
1139
- }));
1140
- var LocalSearchHandler = LocalSearchToolkit.toLayer({
1141
- search_local_search: Effect8.fn(function* ({ query }) {
1142
- const { objects } = yield* DatabaseService5.runQuery(Query.select(Filter.text(query, {
1143
- type: "vector"
1144
- })));
1145
- const results = [
1146
- ...objects
1147
- ];
1148
- const option = yield* Effect8.serviceOption(ContextQueueService);
1149
- if (Option3.isSome(option)) {
1150
- const queueObjects = yield* Effect8.promise(() => option.value.queue.queryObjects());
1151
- results.push(...queueObjects);
1152
- }
1153
- return trim2`
1154
- <local_context>
1155
- ${JSON.stringify(results, null, 2)}
1156
- </local_context>
1157
- `;
1158
- })
1159
- });
1160
- var GraphWriterSchema = class extends Context.Tag("@dxos/assistant/GraphWriterSchema")() {
1161
- };
1162
- var makeGraphWriterToolkit = ({ schema }) => {
1163
- return Toolkit.make(Tool.make("graph_writer", {
1164
- description: "Write to the local graph database",
1165
- parameters: createExtractionSchema(schema).fields,
1166
- success: Schema8.Unknown,
1167
- failure: Schema8.Never,
1168
- dependencies: [
1169
- DatabaseService5,
1170
- ContextQueueService
1171
- ]
1172
- }).annotateContext(Context.make(GraphWriterSchema, {
1173
- schema
1174
- })));
1175
- };
1176
- var makeGraphWriterHandler = (toolkit, { onAppend } = {}) => {
1177
- const { schema } = Context.get(toolkit.tools.graph_writer.annotations, GraphWriterSchema);
1178
- return toolkit.toLayer({
1179
- graph_writer: Effect8.fn(function* (input) {
1180
- const { db } = yield* DatabaseService5;
1181
- const { queue } = yield* ContextQueueService;
1182
- const data = yield* Effect8.promise(() => sanitizeObjects(schema, input, db, queue));
1183
- yield* Effect8.promise(() => queue.append(data));
1184
- const dxns = data.map((obj) => Obj3.getDXN(obj));
1185
- onAppend?.(dxns);
1186
- return dxns;
1187
- })
1188
- });
1189
- };
1190
- var createExtractionSchema = (types) => {
1191
- return Schema8.Struct({
1192
- ...Object.fromEntries(types.map(preprocessSchema).map((schema, index) => [
1193
- `objects_${getSanitizedSchemaName(types[index])}`,
1194
- Schema8.optional(Schema8.Array(schema)).annotations({
1195
- description: `The objects of type: ${getSchemaDXN(types[index])?.asTypeDXN().type}. ${SchemaAST.getDescriptionAnnotation(types[index].ast).pipe(Option3.getOrElse(() => ""))}`
1196
- })
1197
- ]))
1198
- });
1199
- };
1200
- var getSanitizedSchemaName = (schema) => {
1201
- return getSchemaDXN(schema).asTypeDXN().type.replaceAll(/[^a-zA-Z0-9]+/g, "_");
1202
- };
1203
- var sanitizeObjects = async (types, data, db, queue) => {
1204
- const entries = types.map((type) => data[`objects_${getSanitizedSchemaName(type)}`]?.map((object) => ({
1205
- data: object,
1206
- schema: type
1207
- })) ?? []).flat();
1208
- const idMap = /* @__PURE__ */ new Map();
1209
- const existingIds = /* @__PURE__ */ new Set();
1210
- const enitties = /* @__PURE__ */ new Map();
1211
- const resolveId = (id) => {
1212
- if (ObjectId2.isValid(id)) {
1213
- existingIds.add(id);
1214
- return DXN2.fromLocalObjectId(id);
1215
- }
1216
- const mappedId = idMap.get(id);
1217
- if (mappedId) {
1218
- return DXN2.fromLocalObjectId(mappedId);
1219
- }
1220
- return void 0;
1221
- };
1222
- const res = entries.map((entry) => {
1223
- if (ObjectId2.isValid(entry.data.id)) {
1224
- return entry;
1225
- }
1226
- idMap.set(entry.data.id, ObjectId2.random());
1227
- entry.data.id = idMap.get(entry.data.id);
1228
- return entry;
1229
- }).map((entry) => {
1230
- const data2 = deepMapValues(entry.data, (value, recurse) => {
1231
- if (isEncodedReference(value)) {
1232
- const ref = value["/"];
1233
- const id = resolveId(ref);
1234
- if (id) {
1235
- return {
1236
- "/": id.toString()
1237
- };
1238
- } else {
1239
- return {
1240
- "/": `search:?q=${encodeURIComponent(ref)}`
1241
- };
1242
- }
1243
- }
1244
- return recurse(value);
1245
- });
1246
- if (getEntityKind(entry.schema) === "relation") {
1247
- const sourceDxn = resolveId(data2.source);
1248
- if (!sourceDxn) {
1249
- log4.warn("source not found", {
1250
- source: data2.source
1251
- }, {
1252
- F: __dxlog_file4,
1253
- L: 281,
1254
- S: void 0,
1255
- C: (f, a) => f(...a)
1256
- });
1257
- }
1258
- const targetDxn = resolveId(data2.target);
1259
- if (!targetDxn) {
1260
- log4.warn("target not found", {
1261
- target: data2.target
1262
- }, {
1263
- F: __dxlog_file4,
1264
- L: 285,
1265
- S: void 0,
1266
- C: (f, a) => f(...a)
1267
- });
1268
- }
1269
- delete data2.source;
1270
- delete data2.target;
1271
- data2[RelationSourceDXNId] = sourceDxn;
1272
- data2[RelationTargetDXNId] = targetDxn;
1269
+ publishedDate: "2024-02-08T02:20:22.000Z",
1270
+ author: "RoboZoom",
1271
+ score: 0.37371376156806946,
1272
+ text: "\n \n \n \n \n \n \n \n \n \n \nGitHub Copilot\n \nWrite better code with AI\n \n \n \n \n \n \nGitHub Models\n \nNew\n \n \nManage and compare prompts\n \n \n \n \n \n \nGitHub Advanced Security\n \nFind and fix vulnerabilities\n \n \n \n \n \n \nActions\n \nAutomate any workflow\n \n \n \n \n \n \nCodespaces\n \nInstant dev environments\n \n \n \n \n \n \n \n \n \n \nIssues\n \nPlan and track work\n \n \n \n \n \n \nCode Review\n \nManage code changes\n \n \n \n \n \n \nDiscussions\n \nCollaborate outside of code\n \n \n \n \n \n \nCode Search\n \nFind more, search less\n \n \n \n \n \n \n \n \n \n \n Explore \n \n \nLearning Pathways\n \n \n \nEvents &amp; Webinars\n \n \n \nEbooks &amp; Whitepapers\n \n \n \nCustomer Stories\n \n \n \nPartners\n \n \n \nExecutive Insights\n \n \n \n \n \n \n \n \n \n \n \n \nGitHub Sponsors\n \nFund open source developers\n \n \n \n \n \n \n \n \n \n \nThe ReadME Project\n \nGitHub community articles\n \n \n \n \n \n \n \n \n \n \n \n \n \nEnterprise platform\n \nAI-powered developer platform\n \n \n \n \n \n \n Pricing \n \n \n \n \n \nSign up\n \n \n",
1273
+ image: "https://opengraph.githubassets.com/2388498497e355faeecdd0ebc0ae18ac0680ba329b5f7030aa21bc38ddaa6b8b/RoboZoom/knowledge_management",
1274
+ favicon: "https://github.com/fluidicon.png"
1275
+ },
1276
+ {
1277
+ id: "https://creati.ai/ai-tools/sciphi/",
1278
+ title: "SciPhi: Build, Deploy, and Optimize AI Systems | Creati.ai",
1279
+ url: "https://creati.ai/ai-tools/sciphi/",
1280
+ publishedDate: "2024-07-01T00:00:00.000Z",
1281
+ author: "",
1282
+ score: 0.37101393938064575,
1283
+ text: "SciPhi simplifies building, deploying, and optimizing Retrieval-Augmented Generation (RAG) systems, empowering developers to focus on AI innovation. Added on: Social &amp; Email: Platform: SciPhi SciPhi simplifies building, deploying, and optimizing Retrieval-Augmented Generation (RAG) systems, empowering developers to focus on AI innovation. Added on: Social &amp; Email: Platform: What is SciPhi? SciPhi is an open-source platform designed to simplify the building, deploying, and scaling of Retrieval-Augmented Generation (RAG) systems. It provides an end-to-end solution for developers, enabling them to focus on AI innovation without worrying about the underlying infrastructure. With tools for automated knowledge graph extraction, document and user management, and robust observability, SciPhi ensures efficient and optimized RAG system deployment. Who will use SciPhi? Developers AI Engineers Data Scientists Tech Startups Research Institutions How to use the SciPhi? Step1: Visit the SciPhi website. Step2: Sign up for an account or log in. Step3: Access the platform's dashboard. Step4: Follow guides to build and deploy your RAG system. Step5: Use tools for knowledge graph extraction and management. Step6: Optimize and monitor your system using provided observability features. SciPhi's Core Features &amp; Benefits The Core Features of SciPhi End-to-End RAG System Deployment Automated Knowledge Graph Extraction Document and User Management Robust Observability Tools The Benefits of SciPhi Simplifies AI Development Speeds Up Deployment Time Enhances System Optimization Reduces Infrastructure Complexity SciPhi's Main Use Cases &amp; Applications Building RAG Systems for AI Applications Deploying Knowledge Graphs Managing Large Document Repositories Optimizing AI System Performance FAQs of SciPhi SciPhi is an open-source platform designed to simplify building, deploying, and optimizing Retrieval-Augmented Generation (RAG) systems. SciPhi is intended for developers, AI engineers, data scientists, tech startups, and research institutions. Core features include end-to-end RAG system deployment, automated knowledge graph extraction, document and user management, and robust observability tools. Visit the SciPhi website, sign up for an account, and follow the guides to build and deploy your RAG system. SciPhi supports web platforms. SciPhi simplifies AI development, speeds up deployment time, enhances system optimization, and reduces infrastructure complexity. Yes, alternatives include LangChain, LlamaIndex, Haystack, and Flower. SciPhi supports building RAG systems for AI applications, deploying knowledge graphs, managing large document repositories, and optimizing AI system performance. You can reach out to their support team via their support email provided on the website. SciPhi offers both free and paid plans. Details on pricing can be found on their website. SciPhi Company Information Website: https://www.sciphi.ai Company Name: SciPhi Support Email: [ema",
1284
+ image: "https://cdn-image.creati.ai/ai-tools/product-image/sciphi.webp",
1285
+ favicon: "https://cdn-image.creati.ai/image/Creatiai.ico"
1286
+ },
1287
+ {
1288
+ id: "https://helpjuice.com/blog/open-source-knowledge-base",
1289
+ title: "The 12 Best Open Source Knowledge Base Software for 2024",
1290
+ url: "https://helpjuice.com/blog/open-source-knowledge-base",
1291
+ author: "Zeeshan Khan",
1292
+ text: "\n \n \n \n \n At Helpjuice / \n \n #Software &amp; Alternatives\n May 15 2025 \n 11m read \n \n \n \n \n On the hunt for the perfect knowledge base software that\u2019s open source? This post will walk you through the best options for your business. \n \n \n \n \n There\u2019s no denying that a knowledge base can make a major impact on your organization.\xA0 Whether it's to help provide better support to your customers or to enable your employees to find the information they need to do their job, a finely-tuned knowledge base can make all the difference when it comes to how knowledge and information flows through your business. And with plenty of options on the market out there, there\u2019s certainly no shortage of open source knowledge base software. But how can you tell you\u2019re not investing time into installing and learning new software that your team won't use anyway? How can you avoid the time and effort put into an open source option that you later determine to not be a good fit for your needs?\xA0 It\u2019s simple\u2014do a little research beforehand. We know, we know\u2014you don\u2019t have endless time to invest in that kind of thing (what with a business to run and all). That\u2019s why we\u2019ve created a helpful list of the must-consider open source knowledge base software that companies of all niches, industries, and sizes should consider.\xA0 We\u2019re even throwing in a little helpful knowledge that should equip you with the information needed to choose the right software for you\u2014like what knowledge base software is in the first place, the benefits of open source software, and how to address your unique needs as a company to choose the right software for you.\xA0 Want to skip ahead on some of the basics of open-source knowledge base software?\xA0 Be our guest.\xA0 The best open source knowledge base software includes: \n BookStack \n OpenKM \n myBase \n eXo \n PHPKB \n Documize \n DocuWiki \n phpMyFAQ \n MediaWiki \n xWiki \n TWiki \n TiddlyWiki \n What is an Open Source Knowledge Base? Before we dive into which open-source knowledge base software you should consider for your business, we should probably ensure we\u2019re on the same page about what exactly open-source knowledge base software is.\xA0 First things first, let\u2019s start with the term knowledge base. A knowledge base is a central place that allows structured storage of information where users can search for and access this information. \xA0Knowledge base software should be the key tool that helps make this process seamless, simplified, and efficient. Knowledge base software is designed to help you create and manage your knowledge base to the best of your ability. this usually includes setting up the knowledge base architecture, creating and editing documentation, searching, and analyzing your knowledge base, and more. Ideally, this is the irreplaceable piece of the puzzle that operates your entire knowledge management system that helps orchestrate, manage, and optimize the flow of knowledge within your organization.\xA0 That part seems pretty clear, right? Next, we\u2019ll move on to",
1293
+ image: "https://static.helpjuice.com/helpjuice_production/uploads/upload/image/4752/direct/1636499945090-Open%20Source%20Knowledge%20Base%20Software.jpg",
1294
+ favicon: "https://static.helpjuice.com/assets/favicon-32x32-161f2153235b710a8ed7b9233ed6b195936bdb57bf1310e720f7fea79547cf9d.png"
1295
+ }
1296
+ ],
1297
+ costDollars: {
1298
+ total: 0.015,
1299
+ search: {
1300
+ neural: 5e-3
1301
+ },
1302
+ contents: {
1303
+ text: 0.01
1273
1304
  }
1274
- return {
1275
- data: data2,
1276
- schema: entry.schema
1277
- };
1278
- }).filter((object) => !existingIds.has(object.data.id));
1279
- const { objects: dbObjects } = await db.query(Query.select(Filter.ids(...existingIds))).run();
1280
- const queueObjects = await queue?.getObjectsById([
1281
- ...existingIds
1282
- ]) ?? [];
1283
- const objects = [
1284
- ...dbObjects,
1285
- ...queueObjects
1286
- ].filter(isNonNullable);
1287
- log4.info("objects", {
1288
- dbObjects,
1289
- queueObjects,
1290
- existingIds
1291
- }, {
1292
- F: __dxlog_file4,
1293
- L: 306,
1294
- S: void 0,
1295
- C: (f, a) => f(...a)
1296
- });
1297
- const missing = Array.from(existingIds).filter((id) => !objects.some((object) => object.id === id));
1298
- if (missing.length > 0) {
1299
- throw new Error(`Object IDs do not point to existing objects: ${missing.join(", ")}`);
1300
1305
  }
1301
- return res.flatMap(({ data: data2, schema }) => {
1302
- let skip = false;
1303
- if (RelationSourceDXNId in data2) {
1304
- const id = data2[RelationSourceDXNId].asEchoDXN()?.echoId;
1305
- const obj = objects.find((object) => object.id === id) ?? enitties.get(id);
1306
- if (obj) {
1307
- delete data2[RelationSourceDXNId];
1308
- data2[RelationSourceId] = obj;
1309
- } else {
1310
- skip = true;
1306
+ };
1307
+
1308
+ // src/testing/data/index.ts
1309
+ var SEARCH_RESULTS = [
1310
+ exa_search_1748337321991_default,
1311
+ exa_search_1748337331526_default,
1312
+ exa_search_1748337344119_default
1313
+ ];
1314
+
1315
+ // src/functions/exa/mock.ts
1316
+ var mock_default = defineFunction7({
1317
+ key: "dxos.org/function/exa-mock",
1318
+ name: "Exa mock",
1319
+ description: "Search the web for information",
1320
+ inputSchema: Schema8.Struct({
1321
+ query: Schema8.String.annotations({
1322
+ description: "The query to search for."
1323
+ })
1324
+ }),
1325
+ outputSchema: Schema8.Unknown,
1326
+ handler: Effect8.fnUntraced(function* ({ data: { query } }) {
1327
+ const result = SEARCH_RESULTS.reduce((closest, current) => {
1328
+ if (!current.autopromptString) {
1329
+ return closest;
1311
1330
  }
1312
- }
1313
- if (RelationTargetDXNId in data2) {
1314
- const id = data2[RelationTargetDXNId].asEchoDXN()?.echoId;
1315
- const obj = objects.find((object) => object.id === id) ?? enitties.get(id);
1316
- if (obj) {
1317
- delete data2[RelationTargetDXNId];
1318
- data2[RelationTargetId] = obj;
1319
- } else {
1320
- skip = true;
1331
+ if (!closest) {
1332
+ return current;
1321
1333
  }
1322
- }
1323
- if (!skip) {
1324
- const obj = create(schema, data2);
1325
- enitties.set(obj.id, obj);
1326
- return [
1327
- obj
1328
- ];
1329
- }
1330
- return [];
1331
- });
1332
- };
1333
- var SoftRef = Schema8.Struct({
1334
- "/": Schema8.String
1335
- }).annotations({
1336
- description: "Reference to another object."
1334
+ const dist1 = levenshteinDistance(query, current.autopromptString);
1335
+ const dist2 = levenshteinDistance(query, closest.autopromptString || "");
1336
+ const weight1 = dist1 / Math.max(query.length, current.autopromptString.length);
1337
+ const weight2 = dist2 / Math.max(query.length, closest.autopromptString?.length || 0);
1338
+ return weight1 < weight2 ? current : closest;
1339
+ }, null);
1340
+ return result;
1341
+ })
1337
1342
  });
1338
- var preprocessSchema = (schema) => {
1339
- const isRelationSchema = getEntityKind(schema) === "relation";
1340
- const go = (ast, visited = /* @__PURE__ */ new Set()) => {
1341
- if (visited.has(ast)) {
1342
- return ast;
1343
- }
1344
- visited.add(ast);
1345
- if (SchemaAST.getAnnotation(ast, ReferenceAnnotationId).pipe(Option3.isSome)) {
1346
- return SoftRef.ast;
1343
+ var levenshteinDistance = (str1, str2) => {
1344
+ const m = str1.length;
1345
+ const n = str2.length;
1346
+ const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
1347
+ for (let i = 0; i <= m; i++) {
1348
+ dp[i][0] = i;
1349
+ }
1350
+ for (let j = 0; j <= n; j++) {
1351
+ dp[0][j] = j;
1352
+ }
1353
+ for (let i = 1; i <= m; i++) {
1354
+ for (let j = 1; j <= n; j++) {
1355
+ dp[i][j] = str1[i - 1] === str2[j - 1] ? dp[i - 1][j - 1] : Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1;
1347
1356
  }
1348
- return mapAst(ast, (child) => go(child, visited));
1349
- };
1350
- return Schema8.make(mapAst(schema.ast, (ast) => go(ast))).pipe(Schema8.omit("id"), Schema8.extend(Schema8.Struct({
1351
- id: Schema8.String.annotations({
1352
- description: "The id of this object. Come up with a unique id based on your judgement."
1353
- })
1354
- })), isRelationSchema ? Schema8.extend(Schema8.Struct({
1355
- source: Schema8.String.annotations({
1356
- description: "The id of the source object for this relation."
1357
- }),
1358
- target: Schema8.String.annotations({
1359
- description: "The id of the target object for this relation."
1360
- })
1361
- })) : Function3.identity);
1357
+ }
1358
+ return dp[m][n];
1362
1359
  };
1363
1360
 
1364
- // raw-loader:/__w/dxos/dxos/packages/core/assistant-toolkit/src/functions/research/instructions-research.tpl?raw
1365
- var instructions_research_default = "You are the Research Agent.\n\nThe Research Agent is an expert assistant that conducts in-depth research using real-time web search.\nThe Research Agent outputs results in a structured format matching the schema provided.\n\nThe Research Agent is equipped with the ability to:\n\n- Generate precise and effective search queries \n- Request web pages by query (through a `web_search` tool)\n- Read the full content of retrieved pages\n- Synthesize accurate, clear, and structured answers using reliable information from the retrieved content\n- Search the local database for information using a vector index (through a `local_search` tool)\n\nThe Research Agent always follows these principles:\n\n- Relevance First: The Research Agent only returns facts supported by content in retrieved web pages. The Research Agent never fabricates or guesses information.\n- Summarize, Don't Copy: The Research Agent synthesizes and rephrases content in its own words. The Research Agent quotes only when necessary.\n- Multiple Sources: The Research Agent cross-references at least 2 sources before drawing conclusions, unless the information is directly stated and non-controversial.\n- Transparency: The Research Agent mentions which sources were used and explains how it arrived at conclusions.\n- Accuracy Over Brevity: The Research Agent prefers detailed, technically accurate explanations over shallow summaries.\n- The Research Agent admits uncertainty rather than misleading.\n- The Research Agent picks the most concrete schema types for extracted information.\n- The Research Agent fills schema fields completely with information it is confident about, and omits fields it is not confident about.\n- When outputting results, the Research Agent adds extra data that fits the schema even if not directly related to the user's question.\n- The Research Agent creates relations and references between new objects found and what's already in the database.\n- The Research Agent does not create objects that are already in the database.\n- The Research Agent re-uses existing object IDs as references when enriching existing objects.\n- The Research Agent ALWAYS calls the `graph_writer` at the end to save the data. This conversation will be deleted, so only the data written to the graph will be preserved.\n\nThe Research Agent may be asked for:\n\n- Technical explanations\n- Literature reviews \n- Comparisons\n- Emerging trends\n- Implementation strategies\n\nThe Research Agent begins by interpreting the user's request, then:\n\nThe Research Agent breaks it into sub-questions (if applicable).\n\nFor each sub-question, the Research Agent generates a clear, concise web search query.\n\nThe Research Agent uses `web_search`(query) to retrieve information.\n\nThe Research Agent extracts and synthesizes relevant answers.\n\nThe Research Agent's output includes:\n\n- A clear, structured answer to the user's question\n- A citation list or link list of sources used\n\nOptionally, the Research Agent provides follow-up suggestions or questions for deeper inquiry.\n\nHere's how the Research Agent operates:\n\n1. The Research Agent analyzes the user's request and identifies key topics to search for (3 or more), printing them out.\n2. The Research Agent performs a web search for each topic.\n3. The Research Agent reads and analyzes results, cross references information from multiple sources, and represents conflicting information as ranges of possible values.\n\n4. The Research Agent searches the local database for information using a vector index that might link to the user's question.\n6. The Research Agent creates relations and references between new objects and existing database objects when related, using existing object IDs as references.\n7. The Research Agent selects the most concrete schema types for extracted information, using multiple types as needed, and prints its decision and reasoning.\n5. The Research Agent creates a clear, structured answer to the user's question.\n8. The Research Agent submits results using the specific schema.\n\nIMPORTANT:\n\n- The Research Agent always runs the `local_search` tool to search the local database at least once before submitting results.\n- The Research Agent does not create objects that already exist in the database.\n- Ids that are not in the database are human-readable strings like `ivan_zhao_1`.\n\nStatus reporting:\n\nThe Research Agent reports its status frequently using the `<status>` tags: <status>Searching for Google Founders</status>\nThe Research Agent reports its status in-between each tool call and before submitting results.\n\n<example>\n\nBased on my research, I can now provide information about Google and it's founders.\n\nThe following objects are already in the database, I will not submit them again, but I'll re-use their IDs as references:\n\n- 01JWRDEHPB5TT2JQQQC15038BT Google\n- 01JWRDEHPA14CYW2NW9FAH6DJJ Larry Page\n- 01JWRDEHPBN0BBJP57B9S108W6 Sergey Brin\n\nI will use the following schema to construct new objects:\n\n- type:dxos.org/type/Organization for Alphabet Inc.\n- type:dxos.org/type/Person for Ivan Zhao\n- type:dxos.org/type/Person for Simon Last\n- dxn:type:dxos.org/relation/Employer for Ivan's employer\n- dxn:type:dxos.org/relation/Employer for Simon's employer\n\n<status>Formatting results</status>\n\n</example>";
1366
-
1367
1361
  // src/functions/research/research-graph.ts
1368
1362
  import * as Effect9 from "effect/Effect";
1369
1363
  import * as Layer2 from "effect/Layer";
1370
1364
  import * as Schema9 from "effect/Schema";
1371
- import { Obj as Obj4, Query as Query2, Ref as Ref2, Type as Type2 } from "@dxos/echo";
1365
+ import { Obj as Obj5, Query as Query2, Ref as Ref2, Type as Type2 } from "@dxos/echo";
1372
1366
  import { Queue } from "@dxos/echo-db";
1373
1367
  import { ContextQueueService as ContextQueueService2, DatabaseService as DatabaseService6, QueueService } from "@dxos/functions";
1374
1368
  var ResearchGraph = Schema9.Struct({
@@ -1383,7 +1377,7 @@ var queryResearchGraph = Effect9.fn("queryResearchGraph")(function* () {
1383
1377
  });
1384
1378
  var createResearchGraph = Effect9.fn("createResearchGraph")(function* () {
1385
1379
  const queue = yield* QueueService.createQueue();
1386
- return yield* DatabaseService6.add(Obj4.make(ResearchGraph, {
1380
+ return yield* DatabaseService6.add(Obj5.make(ResearchGraph, {
1387
1381
  queue: Ref2.fromDXN(queue.dxn)
1388
1382
  }));
1389
1383
  });
@@ -1393,21 +1387,25 @@ var contextQueueLayerFromResearchGraph = Layer2.unwrapEffect(Effect9.gen(functio
1393
1387
  return ContextQueueService2.layer(researchQueue);
1394
1388
  }));
1395
1389
 
1390
+ // raw-loader:/__w/dxos/dxos/packages/core/assistant-toolkit/src/functions/research/research-instructions.tpl?raw
1391
+ var research_instructions_default = "You are the Research Agent.\n\nThe Research Agent is an expert assistant that conducts in-depth research using real-time web search.\nThe Research Agent outputs results in a structured format matching the schema provided.\n\nThe Research Agent is equipped with the ability to:\n\n- Generate precise and effective search queries \n- Request web pages by query.\n- Synthesize accurate, clear, and structured answers using reliable information from the retrieved content\n{{#if entityExtraction}}\n- Search the local database for information using a vector index (through a `local_search` tool)\n{{/if}}\n\nThe Research Agent always follows these principles:\n\n- Relevance First: The Research Agent only returns facts supported by content in retrieved web pages. The Research Agent never fabricates or guesses information.\n- Summarize, Don't Copy: The Research Agent synthesizes and rephrases content in its own words. The Research Agent quotes only when necessary.\n- Multiple Sources: The Research Agent cross-references at least 2 sources before drawing conclusions, unless the information is directly stated and non-controversial.\n- Transparency: The Research Agent mentions which sources were used and explains how it arrived at conclusions.\n- Accuracy Over Brevity: The Research Agent prefers detailed, technically accurate explanations over shallow summaries.\n- The Research Agent admits uncertainty rather than misleading.\n{{#if entityExtraction}}\n- The Research Agent picks the most concrete schema types for extracted information.\n- The Research Agent fills schema fields completely with information it is confident about, and omits fields it is not confident about.\n- When outputting results, the Research Agent adds extra data that fits the schema even if not directly related to the user's question.\n- The Research Agent creates relations and references between new objects found and what's already in the database.\n- The Research Agent does not create objects that are already in the database.\n- The Research Agent re-uses existing object IDs as references when enriching existing objects.\n- The Research Agent ALWAYS calls the `graph_writer` at the end to save the data. This conversation will be deleted, so only the data written to the graph will be preserved.\n{{/if}}\n\nThe Research Agent may be asked for:\n\n- Technical explanations\n- Literature reviews \n- Comparisons\n- Emerging trends\n- Implementation strategies\n\nThe Research Agent begins by interpreting the user's request, then:\n\nThe Research Agent breaks it into sub-questions (if applicable).\n\nFor each sub-question, the Research Agent generates a clear, concise web search query.\n\nThe Research Agent extracts and synthesizes relevant answers.\n\nThe Research Agent's output includes:\n\n- A clear, structured answer to the user's question\n- A citation list or link list of sources used\n\nOptionally, the Research Agent provides follow-up suggestions or questions for deeper inquiry.\n\nHere's how the Research Agent operates:\n\n1. The Research Agent analyzes the user's request and identifies key topics to search for (3 or more), printing them out.\n2. The Research Agent performs a web search for each topic.\n3. The Research Agent reads and analyzes results, cross references information from multiple sources, and represents conflicting information as ranges of possible values.\n\n{{#if entityExtraction}}\n4. The Research Agent searches the local database for information using a vector index that might link to the user's question.\n6. The Research Agent creates relations and references between new objects and existing database objects when related, using existing object IDs as references.\n7. The Research Agent selects the most concrete schema types for extracted information, using multiple types as needed, and prints its decision and reasoning.\n5. The Research Agent creates a clear, structured answer to the user's question.\n8. The Research Agent submits results using the specific schema.\n{{/if}}\n\n{{#if entityExtraction}}\nIMPORTANT:\n- The Research Agent always runs the `local_search` tool to search the local database at least once before submitting results.\n- The Research Agent does not create objects that already exist in the database.\n- Ids that are not in the database are human-readable strings like `ivan_zhao_1`.\n{{/if}}\n\nStatus reporting:\n\nThe Research Agent reports its status frequently using the `<status>` tags: <status>Searching for Google Founders</status>\nThe Research Agent reports its status in-between each tool call and before submitting results.\n\n{{#if entityExtraction}}\n<example>\n\nBased on my research, I can now provide information about Google and it's founders.\n\nThe following objects are already in the database, I will not submit them again, but I'll re-use their IDs as references:\n\n- 01JWRDEHPB5TT2JQQQC15038BT Google\n- 01JWRDEHPA14CYW2NW9FAH6DJJ Larry Page\n- 01JWRDEHPBN0BBJP57B9S108W6 Sergey Brin\n\nI will use the following schema to construct new objects:\n\n- type:dxos.org/type/Organization for Alphabet Inc.\n- type:dxos.org/type/Person for Ivan Zhao\n- type:dxos.org/type/Person for Simon Last\n- dxn:type:dxos.org/relation/Employer for Ivan's employer\n- dxn:type:dxos.org/relation/Employer for Simon's employer\n\n<status>Formatting results</status>\n\n</example>\n{{/if}}\n\nLast content block is the full research note -- the result of the research.\n";
1392
+
1396
1393
  // src/functions/research/types.ts
1397
- import { DataType as DataType3 } from "@dxos/schema";
1394
+ import { Text } from "@dxos/schema";
1395
+ import { Event, HasConnection, HasRelationship, LegacyOrganization, LegacyPerson, Project, Task } from "@dxos/types";
1398
1396
  var ResearchDataTypes = [
1399
1397
  // Objects
1400
- DataType3.Event,
1401
- DataType3.LegacyOrganization,
1402
- DataType3.LegacyPerson,
1403
- DataType3.Project,
1404
- DataType3.Task,
1405
- DataType3.Text,
1398
+ Event.Event,
1399
+ LegacyOrganization,
1400
+ Task.Task,
1401
+ Text.Text,
1406
1402
  // Relations
1407
- // TODO(wittjosiah): Until views (e.g. table) support relations this needs to be expressed via organization ref.
1408
- // DataType.Employer,
1409
- DataType3.HasRelationship,
1410
- DataType3.HasConnection
1403
+ // TODO(wittjosiah): Until views (e.g., Table) support relations this needs to be expressed via organization ref.
1404
+ // Employer.Employer,
1405
+ LegacyPerson,
1406
+ Project.Project,
1407
+ HasRelationship.HasRelationship,
1408
+ HasConnection.HasConnection
1411
1409
  ];
1412
1410
 
1413
1411
  // src/functions/research/research.ts
@@ -1415,40 +1413,46 @@ var research_default = defineFunction8({
1415
1413
  key: "dxos.org/function/research",
1416
1414
  name: "Research",
1417
1415
  description: trim3`
1418
- Research the web for information.
1416
+ Search the web to research information about the given subject.
1419
1417
  Inserts structured data into the research graph.
1420
- Will return research summary and the objects created.
1418
+ Creates a research summary and returns the objects created.
1421
1419
  `,
1422
1420
  inputSchema: Schema10.Struct({
1423
1421
  query: Schema10.String.annotations({
1424
1422
  description: trim3`
1425
- The query to search for.
1426
- If doing research on an object, load it first and pass it as a JSON string.
1423
+ The search query.
1424
+ If doing research on an object then load it first and pass it as JSON.
1427
1425
  `
1428
1426
  }),
1429
- researchInstructions: Schema10.optional(Schema10.String).annotations({
1427
+ instructions: Schema10.optional(Schema10.String).annotations({
1430
1428
  description: trim3`
1431
1429
  The instructions for the research agent.
1432
- E.g., preference on fast responses or in-depth analysis, number of web searcher or the objects created.
1433
1430
  `
1434
1431
  }),
1435
1432
  // TOOD(burdon): Move to context.
1436
1433
  mockSearch: Schema10.optional(Schema10.Boolean).annotations({
1437
1434
  description: "Whether to use the mock search tool.",
1438
1435
  default: false
1436
+ }),
1437
+ entityExtraction: Schema10.optional(Schema10.Boolean).annotations({
1438
+ description: trim3`
1439
+ Whether to extract structured entities from the research.
1440
+ Experimental feature only enable if user explicitly requests it.
1441
+ `,
1442
+ default: false
1439
1443
  })
1440
1444
  }),
1441
1445
  outputSchema: Schema10.Struct({
1442
- note: Schema10.optional(Schema10.String).annotations({
1443
- description: "A note from the research agent."
1446
+ document: Schema10.optional(Schema10.String).annotations({
1447
+ description: "The generated research document."
1444
1448
  }),
1445
1449
  objects: Schema10.Array(Schema10.Unknown).annotations({
1446
- description: "The structured objects created as a result of the research."
1450
+ description: "Structured objects created during the research process."
1447
1451
  })
1448
1452
  }),
1449
- handler: Effect10.fnUntraced(function* ({ data: { query, mockSearch, researchInstructions } }) {
1453
+ handler: Effect10.fnUntraced(function* ({ data: { query, instructions: instructions6, mockSearch = false, entityExtraction = false } }) {
1450
1454
  if (mockSearch) {
1451
- const mockPerson = yield* DatabaseService7.add(Obj5.make(DataType4.Person, {
1455
+ const mockPerson = yield* DatabaseService7.add(Obj6.make(Person.Person, {
1452
1456
  preferredName: "John Doe",
1453
1457
  emails: [
1454
1458
  {
@@ -1462,13 +1466,12 @@ var research_default = defineFunction8({
1462
1466
  ]
1463
1467
  }));
1464
1468
  return {
1465
- note: trim3`
1466
- The research run in test-mode and was mocked.
1467
- Proceed as usual.
1468
- We reference John Doe to test reference: ${Obj5.getDXN(mockPerson)}
1469
+ document: trim3`
1470
+ The research ran in test-mode and was mocked. Proceed as usual.
1471
+ We reference John Doe to test reference: ${Obj6.getDXN(mockPerson)}
1469
1472
  `,
1470
1473
  objects: [
1471
- Obj5.toJSON(mockPerson)
1474
+ Obj6.toJSON(mockPerson)
1472
1475
  ]
1473
1476
  };
1474
1477
  }
@@ -1476,38 +1479,39 @@ var research_default = defineFunction8({
1476
1479
  indexes: true
1477
1480
  });
1478
1481
  yield* TracingService4.emitStatus({
1479
- message: "Researching..."
1480
- });
1481
- const objectDXNs = [];
1482
- const GraphWriterToolkit = makeGraphWriterToolkit({
1483
- schema: ResearchDataTypes
1484
- });
1485
- const GraphWriterHandler = makeGraphWriterHandler(GraphWriterToolkit, {
1486
- onAppend: (dxns) => objectDXNs.push(...dxns)
1482
+ message: "Starting research..."
1487
1483
  });
1488
1484
  const NativeWebSearch = Toolkit2.make(AnthropicTool.WebSearch_20250305({}));
1489
- const toolkit = yield* createToolkit2({
1490
- toolkit: Toolkit2.merge(LocalSearchToolkit, GraphWriterToolkit, NativeWebSearch)
1491
- }).pipe(Effect10.provide(Layer3.mergeAll(
1492
- //
1493
- GraphWriterHandler,
1494
- LocalSearchHandler
1495
- ).pipe(Layer3.provide(contextQueueLayerFromResearchGraph))));
1485
+ let toolkit = NativeWebSearch;
1486
+ let handlers = Layer3.empty;
1487
+ const objectDXNs = [];
1488
+ if (entityExtraction) {
1489
+ const GraphWriterToolkit = makeGraphWriterToolkit({
1490
+ schema: ResearchDataTypes
1491
+ });
1492
+ const GraphWriterHandler = makeGraphWriterHandler(GraphWriterToolkit, {
1493
+ onAppend: (dxns) => objectDXNs.push(...dxns)
1494
+ });
1495
+ toolkit = Toolkit2.merge(toolkit, LocalSearchToolkit, GraphWriterToolkit);
1496
+ handlers = Layer3.mergeAll(handlers, LocalSearchHandler, GraphWriterHandler).pipe(Layer3.provide(contextQueueLayerFromResearchGraph));
1497
+ }
1498
+ const finishedToolkit = yield* createToolkit2({
1499
+ toolkit
1500
+ }).pipe(Effect10.provide(handlers));
1496
1501
  const session = new AiSession2();
1497
1502
  const result = yield* session.run({
1498
1503
  prompt: query,
1499
- system: instructions_research_default + (researchInstructions ? `
1500
-
1501
- <research_instructions>${researchInstructions}</research_instructions>` : ""),
1502
- toolkit,
1504
+ system: join(Template2.process(research_instructions_default, {
1505
+ entityExtraction
1506
+ }), instructions6 && `<instructions>${instructions6}</instructions>`),
1507
+ toolkit: finishedToolkit,
1503
1508
  observer: GenerationObserver2.fromPrinter(new ConsolePrinter2({
1504
1509
  tag: "research"
1505
1510
  }))
1506
1511
  });
1507
- const note = result.at(-1)?.blocks.filter((block) => block._tag === "text").at(-1)?.text;
1508
- const objects = yield* Effect10.forEach(objectDXNs, (dxn) => DatabaseService7.resolve(dxn)).pipe(Effect10.map(Array6.map((obj) => Obj5.toJSON(obj))));
1512
+ const objects = yield* Effect10.forEach(objectDXNs, (dxn) => DatabaseService7.resolve(dxn)).pipe(Effect10.map(Array6.map((obj) => Obj6.toJSON(obj))));
1509
1513
  return {
1510
- note,
1514
+ document: extractLastTextBlock(result),
1511
1515
  objects
1512
1516
  };
1513
1517
  }, Effect10.provide(Layer3.mergeAll(
@@ -1520,7 +1524,7 @@ var research_default = defineFunction8({
1520
1524
  makeToolExecutionServiceFromFunctions(Toolkit2.make(), Layer3.empty)
1521
1525
  ).pipe(Layer3.provide(
1522
1526
  // TODO(dmaretskyi): This should be provided by environment.
1523
- Layer3.mergeAll(FunctionInvocationService.layerTestMocked({
1527
+ Layer3.mergeAll(FunctionInvocationServiceLayerTestMocked({
1524
1528
  functions: [
1525
1529
  exa_default,
1526
1530
  mock_default
@@ -1528,10 +1532,14 @@ var research_default = defineFunction8({
1528
1532
  }))
1529
1533
  ))))
1530
1534
  });
1535
+ var join = (...strings) => strings.filter(Boolean).join("\n\n");
1536
+ var extractLastTextBlock = (result) => {
1537
+ return Function4.pipe(result, Array6.last, Option4.map(Function4.flow((_) => _.blocks, Array6.reverse, Array6.dropWhile((_) => _._tag === "summary"), Array6.takeWhile((_) => _._tag === "text"), Array6.reverse, Array6.map((_) => _.text), Array6.reduce("", String10.concat))), Option4.getOrElse(() => ""));
1538
+ };
1531
1539
 
1532
1540
  // src/functions/research/index.ts
1533
1541
  (function(Research2) {
1534
- Research2.create = create_document_default;
1542
+ Research2.create = document_create_default;
1535
1543
  Research2.research = research_default;
1536
1544
  })(Research || (Research = {}));
1537
1545
  var Research;
@@ -1543,7 +1551,7 @@ var entity_extraction_default = defineFunction9({
1543
1551
  name: "Entity Extraction",
1544
1552
  description: "Extracts entities from emails and transcripts.",
1545
1553
  inputSchema: Schema11.Struct({
1546
- source: DataType5.Message.annotations({
1554
+ source: Message2.Message.annotations({
1547
1555
  description: "Email or transcript to extract entities from."
1548
1556
  }),
1549
1557
  // TODO(dmaretskyi): Consider making this an array of blueprints instead.
@@ -1552,7 +1560,7 @@ var entity_extraction_default = defineFunction9({
1552
1560
  })
1553
1561
  }),
1554
1562
  outputSchema: Schema11.Struct({
1555
- entities: Schema11.optional(Schema11.Array(Obj6.Any).annotations({
1563
+ entities: Schema11.optional(Schema11.Array(Obj7.Any).annotations({
1556
1564
  description: "Extracted entities."
1557
1565
  }))
1558
1566
  }),
@@ -1563,7 +1571,7 @@ var entity_extraction_default = defineFunction9({
1563
1571
  const created = [];
1564
1572
  const GraphWriterToolkit = makeGraphWriterToolkit({
1565
1573
  schema: [
1566
- DataType5.LegacyOrganization
1574
+ LegacyOrganization2
1567
1575
  ]
1568
1576
  }).pipe();
1569
1577
  const GraphWriterHandler = makeGraphWriterHandler(GraphWriterToolkit, {
@@ -1585,9 +1593,9 @@ var entity_extraction_default = defineFunction9({
1585
1593
  if (created.length > 1) {
1586
1594
  throw new Error("Multiple organizations created");
1587
1595
  } else if (created.length === 1) {
1588
- organization = yield* DatabaseService8.resolve(created[0], DataType5.Organization);
1589
- Obj6.getMeta(organization).tags ??= [];
1590
- Obj6.getMeta(organization).tags.push(...Obj6.getMeta(source)?.tags ?? []);
1596
+ organization = yield* DatabaseService8.resolve(created[0], Organization.Organization);
1597
+ Obj7.getMeta(organization).tags ??= [];
1598
+ Obj7.getMeta(organization).tags.push(...Obj7.getMeta(source)?.tags ?? []);
1591
1599
  contact.organization = Ref3.make(organization);
1592
1600
  }
1593
1601
  }
@@ -1599,7 +1607,7 @@ var entity_extraction_default = defineFunction9({
1599
1607
  };
1600
1608
  }, Effect11.provide(Layer4.mergeAll(AiService3.model("@anthropic/claude-sonnet-4-0"), makeToolResolverFromFunctions2([], Toolkit3.make()), makeToolExecutionServiceFromFunctions2(Toolkit3.make(), Layer4.empty)).pipe(Layer4.provide(
1601
1609
  // TODO(dmaretskyi): This should be provided by environment.
1602
- Layer4.mergeAll(FunctionInvocationService2.layerTest())
1610
+ Layer4.mergeAll(FunctionInvocationServiceLayerTest())
1603
1611
  ))))
1604
1612
  });
1605
1613
  var extractContact = Effect11.fn("extractContact")(function* (message) {
@@ -1610,13 +1618,13 @@ var extractContact = Effect11.fn("extractContact")(function* (message) {
1610
1618
  sender: message.sender
1611
1619
  }, {
1612
1620
  F: __dxlog_file5,
1613
- L: 97,
1621
+ L: 99,
1614
1622
  S: this,
1615
1623
  C: (f, a) => f(...a)
1616
1624
  });
1617
1625
  return void 0;
1618
1626
  }
1619
- const { objects: existingContacts } = yield* DatabaseService8.runQuery(Filter2.type(DataType5.Person));
1627
+ const { objects: existingContacts } = yield* DatabaseService8.runQuery(Filter2.type(Person2.Person));
1620
1628
  const existingContact = existingContacts.find((contact) => contact.emails?.some((contactEmail) => contactEmail.value === email));
1621
1629
  if (existingContact) {
1622
1630
  log5.info("Contact already exists", {
@@ -1624,15 +1632,15 @@ var extractContact = Effect11.fn("extractContact")(function* (message) {
1624
1632
  existingContact
1625
1633
  }, {
1626
1634
  F: __dxlog_file5,
1627
- L: 110,
1635
+ L: 112,
1628
1636
  S: this,
1629
1637
  C: (f, a) => f(...a)
1630
1638
  });
1631
1639
  return existingContact;
1632
1640
  }
1633
- const newContact = Obj6.make(DataType5.Person, {
1634
- [Obj6.Meta]: {
1635
- tags: Obj6.getMeta(message)?.tags
1641
+ const newContact = Obj7.make(Person2.Person, {
1642
+ [Obj7.Meta]: {
1643
+ tags: Obj7.getMeta(message)?.tags
1636
1644
  },
1637
1645
  emails: [
1638
1646
  {
@@ -1650,7 +1658,7 @@ var extractContact = Effect11.fn("extractContact")(function* (message) {
1650
1658
  email
1651
1659
  }, {
1652
1660
  F: __dxlog_file5,
1653
- L: 128,
1661
+ L: 130,
1654
1662
  S: this,
1655
1663
  C: (f, a) => f(...a)
1656
1664
  });
@@ -1660,11 +1668,11 @@ var extractContact = Effect11.fn("extractContact")(function* (message) {
1660
1668
  emailDomain
1661
1669
  }, {
1662
1670
  F: __dxlog_file5,
1663
- L: 132,
1671
+ L: 134,
1664
1672
  S: this,
1665
1673
  C: (f, a) => f(...a)
1666
1674
  });
1667
- const { objects: existingOrganisations } = yield* DatabaseService8.runQuery(Filter2.type(DataType5.Organization));
1675
+ const { objects: existingOrganisations } = yield* DatabaseService8.runQuery(Filter2.type(Organization.Organization));
1668
1676
  const matchingOrg = existingOrganisations.find((org) => {
1669
1677
  if (org.website) {
1670
1678
  try {
@@ -1677,7 +1685,7 @@ var extractContact = Effect11.fn("extractContact")(function* (message) {
1677
1685
  error: e
1678
1686
  }, {
1679
1687
  F: __dxlog_file5,
1680
- L: 150,
1688
+ L: 152,
1681
1689
  S: this,
1682
1690
  C: (f, a) => f(...a)
1683
1691
  });
@@ -1691,7 +1699,7 @@ var extractContact = Effect11.fn("extractContact")(function* (message) {
1691
1699
  organization: matchingOrg
1692
1700
  }, {
1693
1701
  F: __dxlog_file5,
1694
- L: 158,
1702
+ L: 160,
1695
1703
  S: this,
1696
1704
  C: (f, a) => f(...a)
1697
1705
  });
@@ -1711,16 +1719,16 @@ import * as FetchHttpClient2 from "@effect/platform/FetchHttpClient";
1711
1719
  import * as HttpClient from "@effect/platform/HttpClient";
1712
1720
  import * as Array9 from "effect/Array";
1713
1721
  import * as Effect13 from "effect/Effect";
1714
- import * as Function4 from "effect/Function";
1722
+ import * as Function5 from "effect/Function";
1715
1723
  import * as Schema12 from "effect/Schema";
1716
- import { Filter as Filter4, Obj as Obj8, Query as Query4, Ref as Ref5 } from "@dxos/echo";
1724
+ import { Filter as Filter4, Obj as Obj9, Query as Query4, Ref as Ref5 } from "@dxos/echo";
1717
1725
  import { DatabaseService as DatabaseService10, defineFunction as defineFunction10, withAuthorization } from "@dxos/functions";
1718
1726
  import { log as log7 } from "@dxos/log";
1719
- import { DataType as DataType6 } from "@dxos/schema";
1727
+ import { Person as Person3, Project as Project2, Task as Task2 } from "@dxos/types";
1720
1728
 
1721
1729
  // src/sync/sync.ts
1722
1730
  import * as Effect12 from "effect/Effect";
1723
- import { Filter as Filter3, Obj as Obj7, Query as Query3, Ref as Ref4 } from "@dxos/echo";
1731
+ import { Filter as Filter3, Obj as Obj8, Query as Query3, Ref as Ref4 } from "@dxos/echo";
1724
1732
  import { DatabaseService as DatabaseService9 } from "@dxos/functions";
1725
1733
  import { failedInvariant } from "@dxos/invariant";
1726
1734
  import { log as log6 } from "@dxos/log";
@@ -1732,7 +1740,7 @@ var syncObjects = Effect12.fn("syncObjects")(function* (objs, { foreignKeyId })
1732
1740
  if (!Ref4.isRef(obj[key])) continue;
1733
1741
  const ref = obj[key];
1734
1742
  if (!ref.target) continue;
1735
- if (Obj7.getDXN(ref.target).isLocalObjectId()) {
1743
+ if (Obj8.getDXN(ref.target).isLocalObjectId()) {
1736
1744
  const [target] = yield* syncObjects([
1737
1745
  ref.target
1738
1746
  ], {
@@ -1741,8 +1749,8 @@ var syncObjects = Effect12.fn("syncObjects")(function* (objs, { foreignKeyId })
1741
1749
  obj[key] = Ref4.make(target);
1742
1750
  }
1743
1751
  }
1744
- const schema = Obj7.getSchema(obj) ?? failedInvariant("No schema.");
1745
- const foreignId = Obj7.getKeys(obj, foreignKeyId)[0]?.id ?? failedInvariant("No foreign key.");
1752
+ const schema = Obj8.getSchema(obj) ?? failedInvariant("No schema.");
1753
+ const foreignId = Obj8.getKeys(obj, foreignKeyId)[0]?.id ?? failedInvariant("No foreign key.");
1746
1754
  const { objects: [existing] } = yield* DatabaseService9.runQuery(Query3.select(Filter3.foreignKeys(schema, [
1747
1755
  {
1748
1756
  source: foreignKeyId,
@@ -1750,9 +1758,9 @@ var syncObjects = Effect12.fn("syncObjects")(function* (objs, { foreignKeyId })
1750
1758
  }
1751
1759
  ])));
1752
1760
  log6("sync object", {
1753
- type: Obj7.getTypename(obj),
1761
+ type: Obj8.getTypename(obj),
1754
1762
  foreignId,
1755
- existing: existing ? Obj7.getDXN(existing) : void 0
1763
+ existing: existing ? Obj8.getDXN(existing) : void 0
1756
1764
  }, {
1757
1765
  F: __dxlog_file6,
1758
1766
  L: 47,
@@ -1782,9 +1790,9 @@ var copyObjectData = (existing, newObj) => {
1782
1790
  delete existing[key];
1783
1791
  }
1784
1792
  }
1785
- for (const foreignKey of Obj7.getMeta(newObj).keys) {
1786
- Obj7.deleteKeys(existing, foreignKey.source);
1787
- Obj7.getMeta(existing).keys.push({
1793
+ for (const foreignKey of Obj8.getMeta(newObj).keys) {
1794
+ Obj8.deleteKeys(existing, foreignKey.source);
1795
+ Obj8.getMeta(existing).keys.push({
1788
1796
  ...foreignKey
1789
1797
  });
1790
1798
  }
@@ -1851,7 +1859,7 @@ var sync_issues_default = defineFunction10({
1851
1859
  const client = yield* HttpClient.HttpClient.pipe(Effect13.map(withAuthorization({
1852
1860
  service: "linear.app"
1853
1861
  })));
1854
- const after = yield* getLatestUpdateTimestamp(data.team, DataType6.Task);
1862
+ const after = yield* getLatestUpdateTimestamp(data.team, Task2.Task);
1855
1863
  log7.info("will fetch", {
1856
1864
  after
1857
1865
  }, {
@@ -1893,10 +1901,10 @@ var getLatestUpdateTimestamp = Effect13.fnUntraced(function* (teamId, dataType)
1893
1901
  id: teamId
1894
1902
  }
1895
1903
  ])));
1896
- return Function4.pipe(existingTasks, Array9.map((task) => Obj8.getKeys(task, LINEAR_UPDATED_AT_KEY).at(0)?.id), Array9.filter((x) => x !== void 0), Array9.reduce("2025-01-01T00:00:00.000Z", (acc, x) => x > acc ? x : acc));
1904
+ return Function5.pipe(existingTasks, Array9.map((task) => Obj9.getKeys(task, LINEAR_UPDATED_AT_KEY).at(0)?.id), Array9.filter((x) => x !== void 0), Array9.reduce("2025-01-01T00:00:00.000Z", (acc, x) => x > acc ? x : acc));
1897
1905
  });
1898
- var mapLinearPerson = (person, { teamId }) => Obj8.make(DataType6.Person, {
1899
- [Obj8.Meta]: {
1906
+ var mapLinearPerson = (person, { teamId }) => Obj9.make(Person3.Person, {
1907
+ [Obj9.Meta]: {
1900
1908
  keys: [
1901
1909
  {
1902
1910
  id: person.id,
@@ -1910,8 +1918,8 @@ var mapLinearPerson = (person, { teamId }) => Obj8.make(DataType6.Person, {
1910
1918
  },
1911
1919
  nickname: person.name
1912
1920
  });
1913
- var mapLinearIssue = (issue, { teamId }) => Obj8.make(DataType6.Task, {
1914
- [Obj8.Meta]: {
1921
+ var mapLinearIssue = (issue, { teamId }) => Obj9.make(Task2.Task, {
1922
+ [Obj9.Meta]: {
1915
1923
  keys: [
1916
1924
  {
1917
1925
  id: issue.id,
@@ -1934,8 +1942,8 @@ var mapLinearIssue = (issue, { teamId }) => Obj8.make(DataType6.Task, {
1934
1942
  })),
1935
1943
  // TODO(dmaretskyi): Sync those (+ linear team as org?).
1936
1944
  // state: issue.state.name,
1937
- project: !issue.project ? void 0 : Ref5.make(DataType6.makeProject({
1938
- [Obj8.Meta]: {
1945
+ project: !issue.project ? void 0 : Ref5.make(Project2.make({
1946
+ [Obj9.Meta]: {
1939
1947
  keys: [
1940
1948
  {
1941
1949
  id: issue.project.id,
@@ -1960,7 +1968,7 @@ var Linear;
1960
1968
  // src/functions/tasks/read.ts
1961
1969
  import * as Effect14 from "effect/Effect";
1962
1970
  import * as Schema13 from "effect/Schema";
1963
- import { ArtifactId as ArtifactId3 } from "@dxos/assistant";
1971
+ import { ArtifactId as ArtifactId4 } from "@dxos/assistant";
1964
1972
  import { DatabaseService as DatabaseService11, defineFunction as defineFunction11 } from "@dxos/functions";
1965
1973
  import { Markdown as Markdown4 } from "@dxos/plugin-markdown/types";
1966
1974
  var read_default2 = defineFunction11({
@@ -1968,7 +1976,7 @@ var read_default2 = defineFunction11({
1968
1976
  name: "Read",
1969
1977
  description: "Read markdown tasks.",
1970
1978
  inputSchema: Schema13.Struct({
1971
- id: ArtifactId3.annotations({
1979
+ id: ArtifactId4.annotations({
1972
1980
  description: "The ID of the document to read."
1973
1981
  })
1974
1982
  }),
@@ -1976,7 +1984,7 @@ var read_default2 = defineFunction11({
1976
1984
  content: Schema13.String
1977
1985
  }),
1978
1986
  handler: Effect14.fn(function* ({ data: { id } }) {
1979
- const doc = yield* DatabaseService11.resolve(ArtifactId3.toDXN(id), Markdown4.Document);
1987
+ const doc = yield* DatabaseService11.resolve(ArtifactId4.toDXN(id), Markdown4.Document);
1980
1988
  const { content } = yield* DatabaseService11.load(doc.content);
1981
1989
  const lines = content.split("\n");
1982
1990
  const len = String(lines.length).length;
@@ -1990,7 +1998,7 @@ var read_default2 = defineFunction11({
1990
1998
  // src/functions/tasks/update.ts
1991
1999
  import * as Effect15 from "effect/Effect";
1992
2000
  import * as Schema14 from "effect/Schema";
1993
- import { ArtifactId as ArtifactId4 } from "@dxos/assistant";
2001
+ import { ArtifactId as ArtifactId5 } from "@dxos/assistant";
1994
2002
  import { DatabaseService as DatabaseService12, defineFunction as defineFunction12 } from "@dxos/functions";
1995
2003
  import { Markdown as Markdown5 } from "@dxos/plugin-markdown/types";
1996
2004
 
@@ -2128,7 +2136,7 @@ var update_default2 = defineFunction12({
2128
2136
  name: "Update markdown",
2129
2137
  description: "Creates and updates tasks in markdown documents.",
2130
2138
  inputSchema: Schema14.Struct({
2131
- id: ArtifactId4.annotations({
2139
+ id: ArtifactId5.annotations({
2132
2140
  description: "The ID of the document to update."
2133
2141
  }),
2134
2142
  operations: Schema14.optional(Schema14.Array(Schema14.Any.annotations({
@@ -2142,7 +2150,7 @@ var update_default2 = defineFunction12({
2142
2150
  })
2143
2151
  }),
2144
2152
  handler: Effect15.fn(function* ({ data: { id, operations = [] } }) {
2145
- const doc = yield* DatabaseService12.resolve(ArtifactId4.toDXN(id), Markdown5.Document);
2153
+ const doc = yield* DatabaseService12.resolve(ArtifactId5.toDXN(id), Markdown5.Document);
2146
2154
  const { content } = yield* DatabaseService12.load(doc.content);
2147
2155
  const taskManager = new MarkdownTasks(content);
2148
2156
  if (operations.length > 0) {
@@ -2172,12 +2180,12 @@ var instructions = trim5`
2172
2180
  When replying to the user, be terse with your comments about design doc handling.
2173
2181
  Do not announce when you read or write the design spec document.
2174
2182
  `;
2175
- var blueprint = Obj9.make(Blueprint.Blueprint, {
2183
+ var blueprint = Obj10.make(Blueprint.Blueprint, {
2176
2184
  key: "dxos.org/blueprint/design",
2177
2185
  name: "Design Spec",
2178
2186
  description: "Preserve the conversation in the design spec.",
2179
2187
  instructions: {
2180
- source: Ref6.make(DataType7.makeText(instructions))
2188
+ source: Ref6.make(Text2.make(instructions))
2181
2189
  },
2182
2190
  tools: [
2183
2191
  Document.read,
@@ -2192,8 +2200,8 @@ var design_default = design_blueprint_default;
2192
2200
  // src/blueprints/discord/discord-blueprint.ts
2193
2201
  import { ToolId as ToolId2 } from "@dxos/ai";
2194
2202
  import { Blueprint as Blueprint2 } from "@dxos/blueprints";
2195
- import { Obj as Obj10, Ref as Ref7 } from "@dxos/echo";
2196
- import { DataType as DataType8 } from "@dxos/schema";
2203
+ import { Obj as Obj11, Ref as Ref7 } from "@dxos/echo";
2204
+ import { Text as Text3 } from "@dxos/schema";
2197
2205
  import { trim as trim6 } from "@dxos/util";
2198
2206
  var instructions2 = trim6`
2199
2207
  You are able to fetch messages from Discord servers.
@@ -2202,12 +2210,12 @@ var instructions2 = trim6`
2202
2210
 
2203
2211
  DXOS serverId: 837138313172353095
2204
2212
  `;
2205
- var blueprint2 = Obj10.make(Blueprint2.Blueprint, {
2213
+ var blueprint2 = Obj11.make(Blueprint2.Blueprint, {
2206
2214
  key: "dxos.org/blueprint/discord",
2207
2215
  name: "Discord",
2208
2216
  description: "Discord integration.",
2209
2217
  instructions: {
2210
- source: Ref7.make(DataType8.makeText(instructions2))
2218
+ source: Ref7.make(Text3.make(instructions2))
2211
2219
  },
2212
2220
  tools: [
2213
2221
  ToolId2.make(Discord.fetch.key)
@@ -2221,8 +2229,8 @@ var discord_default = discord_blueprint_default;
2221
2229
  // src/blueprints/linear/linear-blueprint.ts
2222
2230
  import { ToolId as ToolId3 } from "@dxos/ai";
2223
2231
  import { Blueprint as Blueprint3 } from "@dxos/blueprints";
2224
- import { Obj as Obj11, Ref as Ref8 } from "@dxos/echo";
2225
- import { DataType as DataType9 } from "@dxos/schema";
2232
+ import { Obj as Obj12, Ref as Ref8 } from "@dxos/echo";
2233
+ import { Text as Text4 } from "@dxos/schema";
2226
2234
  import { trim as trim7 } from "@dxos/util";
2227
2235
  var instructions3 = trim7`
2228
2236
  You are able to sync Linear workspaces.
@@ -2232,12 +2240,12 @@ var instructions3 = trim7`
2232
2240
 
2233
2241
  DXOS teamId: 1127c63a-6f77-4725-9229-50f6cd47321c
2234
2242
  `;
2235
- var blueprint3 = Obj11.make(Blueprint3.Blueprint, {
2243
+ var blueprint3 = Obj12.make(Blueprint3.Blueprint, {
2236
2244
  key: "dxos.org/blueprint/linear",
2237
2245
  name: "Linear",
2238
2246
  description: "Syncs Linear workspaces.",
2239
2247
  instructions: {
2240
- source: Ref8.make(DataType9.makeText(instructions3))
2248
+ source: Ref8.make(Text4.make(instructions3))
2241
2249
  },
2242
2250
  tools: [
2243
2251
  Linear.sync
@@ -2251,8 +2259,8 @@ var linear_default = linear_blueprint_default;
2251
2259
  // src/blueprints/planning/planning-blueprint.ts
2252
2260
  import { ToolId as ToolId4 } from "@dxos/ai";
2253
2261
  import { Blueprint as Blueprint4 } from "@dxos/blueprints";
2254
- import { Obj as Obj12, Ref as Ref9 } from "@dxos/echo";
2255
- import { DataType as DataType10 } from "@dxos/schema";
2262
+ import { Obj as Obj13, Ref as Ref9 } from "@dxos/echo";
2263
+ import { Text as Text5 } from "@dxos/schema";
2256
2264
  import { trim as trim8 } from "@dxos/util";
2257
2265
  var instructions4 = trim8`
2258
2266
  You are a task management agent that maintains hierarchical task lists where each line is a task.
@@ -2325,12 +2333,12 @@ var instructions4 = trim8`
2325
2333
  - When creating subtasks, consider the parent task's completion status
2326
2334
  - Be precise with task descriptions and hierarchy levels
2327
2335
  `;
2328
- var blueprint4 = Obj12.make(Blueprint4.Blueprint, {
2336
+ var blueprint4 = Obj13.make(Blueprint4.Blueprint, {
2329
2337
  key: "dxos.org/blueprint/planning",
2330
2338
  name: "Planning",
2331
2339
  description: "Plans and tracks complex tasks with artifact management.",
2332
2340
  instructions: {
2333
- source: Ref9.make(DataType10.makeText(instructions4))
2341
+ source: Ref9.make(Text5.make(instructions4))
2334
2342
  },
2335
2343
  tools: [
2336
2344
  Tasks.read,
@@ -2345,33 +2353,41 @@ var planning_default = planning_blueprint_default;
2345
2353
  // src/blueprints/research/research-blueprint.ts
2346
2354
  import { ToolId as ToolId5 } from "@dxos/ai";
2347
2355
  import { Blueprint as Blueprint5 } from "@dxos/blueprints";
2348
- import { Obj as Obj13, Ref as Ref10 } from "@dxos/echo";
2349
- import { DataType as DataType11 } from "@dxos/schema";
2356
+ import { Obj as Obj14, Ref as Ref10 } from "@dxos/echo";
2357
+ import { Text as Text6 } from "@dxos/schema";
2350
2358
  import { trim as trim9 } from "@dxos/util";
2351
2359
  var instructions5 = trim9`
2352
2360
  {{! Research }}
2353
2361
 
2354
2362
  You are an analyst that does research tasks using tools that scrape the web and create structured data.
2355
- The result of the research is a set of structured entities forming an interconnected graph.
2356
- When you are done, reply with the created objects.
2357
- Do not print the data, instead reply with inline references to the created objects.
2358
- Those will be later substituted with the pills representing the created objects.
2359
- Print the rest of the created objects as block references after the main note.
2360
-
2361
- <example>
2362
- Based on my research, Google was founded by @dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M and @dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK46K31DDW62PBW9H2ZQ
2363
-
2364
- <object><dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn></object>
2365
- <object><dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK46K31DDW62PBW9H2ZQ</dxn></object>
2366
- <object><dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK46K31DDW62PBW92333</dxn></object>
2367
- </example>
2363
+ Structured data extraction is an experimental feature -- only enable it if the user explicitly requests it in the prompt.
2364
+ Prefer updating existing notes instead of creating new ones.
2365
+
2366
+ <strcutured_mode>
2367
+ When you are done, reply with the created objects.
2368
+ Do not print the data, instead reply with inline references to the created objects.
2369
+ Those will be later substituted with the pills representing the created objects.
2370
+ Print the rest of the created objects as block references after the main note.
2371
+
2372
+ <example>
2373
+ Based on my research, Google was founded by @dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M and @dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK46K31DDW62PBW9H2ZQ
2374
+
2375
+ <object><dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn></object>
2376
+ <object><dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK46K31DDW62PBW9H2ZQ</dxn></object>
2377
+ <object><dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK46K31DDW62PBW92333</dxn></object>
2378
+ </example>
2379
+ </structured_mode>
2380
+
2381
+ <unstructured_mode>
2382
+ Reply normally with the text mode of the result of your research.
2383
+ </unstructured_mode>
2368
2384
  `;
2369
- var blueprint5 = Obj13.make(Blueprint5.Blueprint, {
2385
+ var blueprint5 = Obj14.make(Blueprint5.Blueprint, {
2370
2386
  key: "dxos.org/blueprint/research",
2371
2387
  name: "Research",
2372
2388
  description: "Researches the web and creates structured data.",
2373
2389
  instructions: {
2374
- source: Ref10.make(DataType11.makeText(instructions5))
2390
+ source: Ref10.make(Text6.make(instructions5))
2375
2391
  },
2376
2392
  tools: [
2377
2393
  Research.create,
@@ -2386,14 +2402,14 @@ var research_default2 = research_blueprint_default;
2386
2402
  // src/blueprints/websearch/websearch-blueprint.ts
2387
2403
  import { ToolId as ToolId6 } from "@dxos/ai";
2388
2404
  import { Blueprint as Blueprint6 } from "@dxos/blueprints";
2389
- import { Obj as Obj14, Ref as Ref11 } from "@dxos/echo";
2390
- import { DataType as DataType12 } from "@dxos/schema";
2391
- var blueprint6 = Obj14.make(Blueprint6.Blueprint, {
2405
+ import { Obj as Obj15, Ref as Ref11 } from "@dxos/echo";
2406
+ import { Text as Text7 } from "@dxos/schema";
2407
+ var blueprint6 = Obj15.make(Blueprint6.Blueprint, {
2392
2408
  key: "dxos.org/blueprint/web-search",
2393
2409
  name: "Web Search",
2394
2410
  description: "Search the web.",
2395
2411
  instructions: {
2396
- source: Ref11.make(DataType12.makeText(""))
2412
+ source: Ref11.make(Text7.make())
2397
2413
  },
2398
2414
  tools: [
2399
2415
  ToolId6.make("AnthropicWebSearch")
@@ -2445,8 +2461,287 @@ var capabilities = [
2445
2461
  })
2446
2462
  }))
2447
2463
  ];
2464
+
2465
+ // src/toolkits/AssistantToolkit.ts
2466
+ var AssistantToolkit_exports = {};
2467
+ __export(AssistantToolkit_exports, {
2468
+ AssistantToolkit: () => AssistantToolkit,
2469
+ layer: () => layer3,
2470
+ tools: () => tools
2471
+ });
2472
+ import * as Tool2 from "@effect/ai/Tool";
2473
+ import * as Toolkit5 from "@effect/ai/Toolkit";
2474
+ import * as Effect16 from "effect/Effect";
2475
+ import * as Record from "effect/Record";
2476
+ import * as Schema16 from "effect/Schema";
2477
+ import { AiContextService, ArtifactId as ArtifactId6 } from "@dxos/assistant";
2478
+ import { Ref as Ref12 } from "@dxos/echo";
2479
+ import { DatabaseService as DatabaseService13 } from "@dxos/functions";
2480
+ import { trim as trim10 } from "@dxos/util";
2481
+ var AssistantToolkit = Toolkit5.make(Tool2.make("add-to-context", {
2482
+ description: trim10`
2483
+ Adds the object to the chat context.
2484
+ `,
2485
+ parameters: {
2486
+ id: ArtifactId6.annotations({
2487
+ description: "The ID of the document to read."
2488
+ })
2489
+ },
2490
+ success: Schema16.Void,
2491
+ failure: Schema16.Never,
2492
+ dependencies: [
2493
+ AiContextService,
2494
+ DatabaseService13
2495
+ ]
2496
+ }));
2497
+ var tools = Record.keys(AssistantToolkit.tools);
2498
+ var layer3 = () => AssistantToolkit.toLayer({
2499
+ "add-to-context": Effect16.fnUntraced(function* ({ id }) {
2500
+ const { binder } = yield* AiContextService;
2501
+ const { db } = yield* DatabaseService13;
2502
+ const ref = Ref12.fromDXN(ArtifactId6.toDXN(id, db.spaceId));
2503
+ yield* Effect16.promise(() => binder.bind({
2504
+ blueprints: [],
2505
+ objects: [
2506
+ ref
2507
+ ]
2508
+ }));
2509
+ })
2510
+ });
2511
+
2512
+ // src/toolkits/SystemToolkit.ts
2513
+ var SystemToolkit_exports = {};
2514
+ __export(SystemToolkit_exports, {
2515
+ SystemToolkit: () => SystemToolkit,
2516
+ layer: () => layer4,
2517
+ tools: () => tools2
2518
+ });
2519
+ import * as Tool3 from "@effect/ai/Tool";
2520
+ import * as Toolkit6 from "@effect/ai/Toolkit";
2521
+ import * as Effect17 from "effect/Effect";
2522
+ import * as Record2 from "effect/Record";
2523
+ import * as Schema17 from "effect/Schema";
2524
+ import { ArtifactId as ArtifactId7 } from "@dxos/assistant";
2525
+ import { DXN as DXN2, Obj as Obj16, Relation as Relation2, Tag as Tag2, Type as Type4 } from "@dxos/echo";
2526
+ import { DatabaseService as DatabaseService14 } from "@dxos/functions";
2527
+ import { trim as trim11 } from "@dxos/util";
2528
+ var SystemToolkit = Toolkit6.make(
2529
+ //
2530
+ // Schema
2531
+ //
2532
+ Tool3.make("schema-list", {
2533
+ description: trim11`
2534
+ Lists schemas definitions.
2535
+ `,
2536
+ parameters: {
2537
+ // TODO(wittjosiah): Remove this once parameter-less tools are fixed.
2538
+ limit: Schema17.Number
2539
+ },
2540
+ // TODO(dmaretskyi): Effect returns ({ result, encodedResult })
2541
+ success: Schema17.Any,
2542
+ failure: Schema17.Never,
2543
+ dependencies: [
2544
+ DatabaseService14
2545
+ ]
2546
+ }),
2547
+ Tool3.make("schema-add", {
2548
+ description: trim11`
2549
+ Adds a schema to the space.
2550
+ The name will be used when displayed to the user.
2551
+ The typename must be in the format of "example.com/type/Type".
2552
+ `,
2553
+ parameters: {
2554
+ name: Schema17.String,
2555
+ typename: Schema17.String,
2556
+ jsonSchema: Schema17.Any
2557
+ },
2558
+ success: Schema17.Any,
2559
+ failure: Schema17.Never,
2560
+ dependencies: [
2561
+ DatabaseService14
2562
+ ]
2563
+ }),
2564
+ //
2565
+ // Objects
2566
+ //
2567
+ Tool3.make("object-create", {
2568
+ description: trim11`
2569
+ Creates a new object and adds it to the current space.
2570
+ Get the schema from the schema-list tool and ensure that the data matches the corresponding schema.
2571
+ `,
2572
+ parameters: {
2573
+ typename: Schema17.String,
2574
+ data: Schema17.Any
2575
+ },
2576
+ success: Schema17.Any,
2577
+ failure: Schema17.Never,
2578
+ dependencies: [
2579
+ DatabaseService14
2580
+ ]
2581
+ }),
2582
+ Tool3.make("object-remove", {
2583
+ description: trim11`
2584
+ Removes an object or relation from the database.
2585
+ `,
2586
+ parameters: {
2587
+ id: ArtifactId7.annotations({
2588
+ description: "The ID of the object."
2589
+ })
2590
+ },
2591
+ success: Schema17.Any,
2592
+ failure: Schema17.Never,
2593
+ dependencies: [
2594
+ DatabaseService14
2595
+ ]
2596
+ }),
2597
+ //
2598
+ // Relations
2599
+ //
2600
+ Tool3.make("relation-create", {
2601
+ description: trim11`
2602
+ Creates a new relation and adds it to the current space.
2603
+ Get the schema from the schema-list tool and ensure that the data matches the corresponding schema.
2604
+ `,
2605
+ parameters: {
2606
+ typename: Schema17.String,
2607
+ source: ArtifactId7.annotations({
2608
+ description: "The ID of the source object."
2609
+ }),
2610
+ target: ArtifactId7.annotations({
2611
+ description: "The ID of the target object."
2612
+ }),
2613
+ data: Schema17.Any.annotations({
2614
+ description: "The data to be stored in the relation."
2615
+ })
2616
+ },
2617
+ success: Schema17.Any,
2618
+ failure: Schema17.Never,
2619
+ dependencies: [
2620
+ DatabaseService14
2621
+ ]
2622
+ }),
2623
+ //
2624
+ // Tags
2625
+ //
2626
+ Tool3.make("tag-add", {
2627
+ description: trim11`
2628
+ Adds a tag to an object.
2629
+ Tags are objects of type ${Tag2.Tag.typename}.
2630
+ `,
2631
+ parameters: {
2632
+ tagId: ArtifactId7.annotations({
2633
+ description: "The ID of the tag."
2634
+ }),
2635
+ objectId: ArtifactId7.annotations({
2636
+ description: "The ID of the object."
2637
+ })
2638
+ },
2639
+ success: Schema17.Any,
2640
+ failure: Schema17.Never,
2641
+ dependencies: [
2642
+ DatabaseService14
2643
+ ]
2644
+ }),
2645
+ Tool3.make("tag-remove", {
2646
+ description: trim11`
2647
+ Removes a tag from an object.
2648
+ Tags are objects of type ${Tag2.Tag.typename}.
2649
+ `,
2650
+ parameters: {
2651
+ tagId: ArtifactId7.annotations({
2652
+ description: "The ID of the tag."
2653
+ }),
2654
+ objectId: ArtifactId7.annotations({
2655
+ description: "The ID of the object."
2656
+ })
2657
+ },
2658
+ success: Schema17.Any,
2659
+ failure: Schema17.Never,
2660
+ dependencies: [
2661
+ DatabaseService14
2662
+ ]
2663
+ })
2664
+ );
2665
+ var tools2 = Record2.keys(SystemToolkit.tools);
2666
+ var layer4 = () => SystemToolkit.toLayer({
2667
+ "schema-list": Effect17.fnUntraced(function* () {
2668
+ const { db } = yield* DatabaseService14;
2669
+ const schema = yield* Effect17.promise(() => db.schemaRegistry.query({
2670
+ location: [
2671
+ "database",
2672
+ "runtime"
2673
+ ]
2674
+ }).run());
2675
+ return schema.map((schema2) => {
2676
+ const meta = Type4.getMeta(schema2);
2677
+ return {
2678
+ typename: Type4.getTypename(schema2),
2679
+ jsonSchema: Type4.toJsonSchema(schema2),
2680
+ kind: meta?.sourceSchema ? "relation" : "record"
2681
+ };
2682
+ });
2683
+ }),
2684
+ "schema-add": Effect17.fnUntraced(function* ({ name, typename, jsonSchema }) {
2685
+ const { db } = yield* DatabaseService14;
2686
+ yield* Effect17.promise(() => db.schemaRegistry.register([
2687
+ {
2688
+ typename,
2689
+ version: "0.1.0",
2690
+ jsonSchema,
2691
+ name
2692
+ }
2693
+ ]));
2694
+ }),
2695
+ "object-create": Effect17.fnUntraced(function* ({ typename, data }) {
2696
+ const { db } = yield* DatabaseService14;
2697
+ const schema = yield* Effect17.promise(() => db.schemaRegistry.query({
2698
+ typename,
2699
+ location: [
2700
+ "database",
2701
+ "runtime"
2702
+ ]
2703
+ }).first());
2704
+ const object = db.add(Obj16.make(schema, data));
2705
+ return object;
2706
+ }),
2707
+ "object-remove": Effect17.fnUntraced(function* ({ id }) {
2708
+ const { db } = yield* DatabaseService14;
2709
+ const object = yield* DatabaseService14.resolve(DXN2.parse(id));
2710
+ db.remove(object);
2711
+ return object;
2712
+ }),
2713
+ "relation-create": Effect17.fnUntraced(function* ({ typename, source, target, data }) {
2714
+ const { db } = yield* DatabaseService14;
2715
+ const schema = yield* Effect17.promise(() => db.schemaRegistry.query({
2716
+ typename,
2717
+ location: [
2718
+ "database",
2719
+ "runtime"
2720
+ ]
2721
+ }).first());
2722
+ const sourceObj = yield* DatabaseService14.resolve(DXN2.parse(source));
2723
+ const targetObj = yield* DatabaseService14.resolve(DXN2.parse(target));
2724
+ const relation = db.add(Relation2.make(schema, {
2725
+ [Relation2.Source]: sourceObj,
2726
+ [Relation2.Target]: targetObj,
2727
+ ...data
2728
+ }));
2729
+ return relation;
2730
+ }),
2731
+ "tag-add": Effect17.fnUntraced(function* ({ tagId, objectId }) {
2732
+ const object = yield* DatabaseService14.resolve(DXN2.parse(objectId));
2733
+ Obj16.addTag(object, DXN2.parse(tagId).toString());
2734
+ return object;
2735
+ }),
2736
+ "tag-remove": Effect17.fnUntraced(function* ({ tagId, objectId }) {
2737
+ const object = yield* DatabaseService14.resolve(DXN2.parse(objectId));
2738
+ Obj16.removeTag(object, DXN2.parse(tagId).toString());
2739
+ return object;
2740
+ })
2741
+ });
2448
2742
  export {
2449
2743
  Agent,
2744
+ AssistantToolkit_exports as AssistantToolkit,
2450
2745
  design_default as DesignBlueprint,
2451
2746
  Discord,
2452
2747
  discord_default as DiscordBlueprint,
@@ -2463,6 +2758,7 @@ export {
2463
2758
  ResearchDataTypes,
2464
2759
  ResearchGraph,
2465
2760
  Subgraph,
2761
+ SystemToolkit_exports as SystemToolkit,
2466
2762
  Tasks,
2467
2763
  websearch_default as WebSearchBlueprint,
2468
2764
  WebSearchToolkit,