@dxos/assistant 0.8.4-main.84f28bd → 0.8.4-main.a4bbb77

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 (170) hide show
  1. package/dist/lib/browser/chunk-ILL2CN3G.mjs +374 -0
  2. package/dist/lib/browser/chunk-ILL2CN3G.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-UB26N5UF.mjs +89 -0
  4. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +7 -0
  5. package/dist/lib/browser/extraction/index.mjs +272 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +712 -1870
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +13 -0
  11. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +91 -0
  13. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-GVKA7VL3.mjs +376 -0
  15. package/dist/lib/node-esm/chunk-GVKA7VL3.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +273 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +712 -1871
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +14 -0
  22. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +7 -0
  23. package/dist/types/src/conversation/context.d.ts +96 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +28 -31
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  27. package/dist/types/src/conversation/index.d.ts +1 -0
  28. package/dist/types/src/conversation/index.d.ts.map +1 -1
  29. package/dist/types/src/diff.d.ts +15 -0
  30. package/dist/types/src/diff.d.ts.map +1 -0
  31. package/dist/types/src/diff.test.d.ts +2 -0
  32. package/dist/types/src/diff.test.d.ts.map +1 -0
  33. package/dist/types/src/errors.d.ts +75 -0
  34. package/dist/types/src/errors.d.ts.map +1 -0
  35. package/dist/types/src/execution-graph.d.ts +82 -0
  36. package/dist/types/src/execution-graph.d.ts.map +1 -0
  37. package/dist/types/src/execution-graph.test.d.ts +2 -0
  38. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  39. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  40. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  41. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +198 -65
  42. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  43. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  44. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  45. package/dist/types/src/extraction/extraction.d.ts +254 -162
  46. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  47. package/dist/types/src/functions/index.d.ts +2 -0
  48. package/dist/types/src/functions/index.d.ts.map +1 -0
  49. package/dist/types/src/functions/services.d.ts +18 -0
  50. package/dist/types/src/functions/services.d.ts.map +1 -0
  51. package/dist/types/src/index.d.ts +5 -5
  52. package/dist/types/src/index.d.ts.map +1 -1
  53. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  54. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  55. package/dist/types/src/session/error-handling.d.ts +4 -0
  56. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  57. package/dist/types/src/session/format.d.ts +184 -0
  58. package/dist/types/src/session/format.d.ts.map +1 -0
  59. package/dist/types/src/session/format.test.d.ts +2 -0
  60. package/dist/types/src/session/format.test.d.ts.map +1 -0
  61. package/dist/types/src/session/index.d.ts +3 -0
  62. package/dist/types/src/session/index.d.ts.map +1 -1
  63. package/dist/types/src/session/observer.d.ts +22 -0
  64. package/dist/types/src/session/observer.d.ts.map +1 -0
  65. package/dist/types/src/session/session.d.ts +32 -268
  66. package/dist/types/src/session/session.d.ts.map +1 -1
  67. package/dist/types/src/session/toolkit.d.ts +14 -0
  68. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  69. package/dist/types/src/session/version-pin.d.ts +4 -4
  70. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  71. package/dist/types/src/templates/index.d.ts +2 -0
  72. package/dist/types/src/templates/index.d.ts.map +1 -0
  73. package/dist/types/src/templates/system.d.ts +18 -0
  74. package/dist/types/src/templates/system.d.ts.map +1 -0
  75. package/dist/types/src/types.d.ts +13 -0
  76. package/dist/types/src/types.d.ts.map +1 -1
  77. package/dist/types/tsconfig.tsbuildinfo +1 -1
  78. package/package.json +50 -24
  79. package/src/conversation/context.ts +154 -0
  80. package/src/conversation/conversation.ts +89 -73
  81. package/src/conversation/index.ts +1 -0
  82. package/src/diff.test.ts +43 -0
  83. package/src/diff.ts +79 -0
  84. package/src/errors.ts +15 -0
  85. package/src/execution-graph.test.ts +738 -0
  86. package/src/execution-graph.ts +500 -0
  87. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +13 -24
  88. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +27 -21
  89. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
  90. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +17 -7
  91. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +4 -3
  92. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  93. package/src/extraction/quotes.test.ts +3 -3
  94. package/src/extraction/quotes.ts +2 -2
  95. package/src/functions/index.ts +5 -0
  96. package/src/functions/services.ts +153 -0
  97. package/src/index.ts +5 -5
  98. package/src/session/artifact-diff.ts +41 -0
  99. package/src/session/error-handling.ts +40 -0
  100. package/src/session/format.test.ts +60 -0
  101. package/src/session/format.ts +139 -0
  102. package/src/session/index.ts +3 -0
  103. package/src/session/observer.ts +58 -0
  104. package/src/session/session.conversations.json +1 -0
  105. package/src/session/session.test.ts +86 -215
  106. package/src/session/session.ts +163 -539
  107. package/src/session/toolkit.ts +46 -0
  108. package/src/session/version-pin.ts +9 -9
  109. package/src/summarization/summarization.test.ts +86 -106
  110. package/src/templates/format.tpl +60 -0
  111. package/src/templates/index.ts +5 -0
  112. package/src/templates/system.tpl +48 -0
  113. package/src/templates/system.ts +41 -0
  114. package/src/types.ts +45 -1
  115. package/src/typings.d.ts +5 -0
  116. package/dist/types/bin/chat.d.ts +0 -2
  117. package/dist/types/bin/chat.d.ts.map +0 -1
  118. package/dist/types/src/blueprint/blueprint.d.ts +0 -41
  119. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  120. package/dist/types/src/blueprint/index.d.ts +0 -3
  121. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  122. package/dist/types/src/blueprint/registry.d.ts +0 -7
  123. package/dist/types/src/blueprint/registry.d.ts.map +0 -1
  124. package/dist/types/src/context/binder.d.ts +0 -34
  125. package/dist/types/src/context/binder.d.ts.map +0 -1
  126. package/dist/types/src/context/binding.d.ts +0 -38
  127. package/dist/types/src/context/binding.d.ts.map +0 -1
  128. package/dist/types/src/context/index.d.ts +0 -3
  129. package/dist/types/src/context/index.d.ts.map +0 -1
  130. package/dist/types/src/research/exa.d.ts +0 -7
  131. package/dist/types/src/research/exa.d.ts.map +0 -1
  132. package/dist/types/src/research/graph.d.ts +0 -41
  133. package/dist/types/src/research/graph.d.ts.map +0 -1
  134. package/dist/types/src/research/graph.test.d.ts +0 -2
  135. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  136. package/dist/types/src/research/index.d.ts +0 -4
  137. package/dist/types/src/research/index.d.ts.map +0 -1
  138. package/dist/types/src/research/research.d.ts +0 -10
  139. package/dist/types/src/research/research.d.ts.map +0 -1
  140. package/dist/types/src/research/research.test.d.ts +0 -2
  141. package/dist/types/src/research/research.test.d.ts.map +0 -1
  142. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  143. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  144. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  145. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  146. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  147. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  148. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  149. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  150. package/dist/types/src/testing/index.d.ts +0 -3
  151. package/dist/types/src/testing/index.d.ts.map +0 -1
  152. package/src/blueprint/blueprint.ts +0 -75
  153. package/src/blueprint/index.ts +0 -6
  154. package/src/blueprint/registry.ts +0 -15
  155. package/src/context/binder.ts +0 -101
  156. package/src/context/binding.ts +0 -31
  157. package/src/context/index.ts +0 -6
  158. package/src/research/exa.ts +0 -100
  159. package/src/research/graph.test.ts +0 -15
  160. package/src/research/graph.ts +0 -337
  161. package/src/research/index.ts +0 -7
  162. package/src/research/instructions-research.tpl +0 -97
  163. package/src/research/research.test.ts +0 -190
  164. package/src/research/research.ts +0 -90
  165. package/src/session/version-pin.test.ts +0 -26
  166. package/src/testing/exa-search-1748337321991.ts +0 -131
  167. package/src/testing/exa-search-1748337331526.ts +0 -144
  168. package/src/testing/exa-search-1748337344119.ts +0 -133
  169. package/src/testing/index.ts +0 -11
  170. package/src/typedefs.d.ts +0 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/assistant",
3
- "version": "0.8.4-main.84f28bd",
3
+ "version": "0.8.4-main.a4bbb77",
4
4
  "description": "Natural language interface to DXOS",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -10,43 +10,69 @@
10
10
  "type": "module",
11
11
  "exports": {
12
12
  ".": {
13
+ "source": "./src/index.ts",
13
14
  "types": "./dist/types/src/index.d.ts",
14
15
  "browser": "./dist/lib/browser/index.mjs",
15
16
  "node": "./dist/lib/node-esm/index.mjs"
17
+ },
18
+ "./extraction": {
19
+ "source": "./src/extraction/index.ts",
20
+ "types": "./dist/types/src/extraction/index.d.ts",
21
+ "browser": "./dist/lib/browser/extraction/index.mjs",
22
+ "node": "./dist/lib/node-esm/extraction/index.mjs"
16
23
  }
17
24
  },
18
25
  "types": "dist/types/src/index.d.ts",
26
+ "typesVersions": {
27
+ "*": {
28
+ "types": [
29
+ "dist/types/src/types/index.d.ts"
30
+ ],
31
+ "extraction": [
32
+ "dist/types/src/extraction/index.d.ts"
33
+ ]
34
+ }
35
+ },
19
36
  "files": [
20
37
  "dist",
21
38
  "src"
22
39
  ],
23
40
  "dependencies": {
24
- "@preact/signals-core": "^1.9.0",
41
+ "@automerge/automerge": "3.1.2",
42
+ "@effect/ai": "0.29.1",
43
+ "@effect/ai-anthropic": "^0.19.2",
44
+ "@effect/experimental": "0.56.0",
45
+ "@effect/platform": "^0.92.1",
46
+ "@effect/platform-node": "^0.98.3",
47
+ "@preact/signals-core": "^1.12.1",
25
48
  "@xenova/transformers": "^2.17.2",
26
49
  "chalk": "^4.1.0",
27
- "exa-js": "^1.5.12",
28
- "@dxos/ai": "0.8.4-main.84f28bd",
29
- "@dxos/artifact": "0.8.4-main.84f28bd",
30
- "@dxos/async": "0.8.4-main.84f28bd",
31
- "@dxos/debug": "0.8.4-main.84f28bd",
32
- "@dxos/echo": "0.8.4-main.84f28bd",
33
- "@dxos/context": "0.8.4-main.84f28bd",
34
- "@dxos/echo-db": "0.8.4-main.84f28bd",
35
- "@dxos/echo-protocol": "0.8.4-main.84f28bd",
36
- "@dxos/echo-schema": "0.8.4-main.84f28bd",
37
- "@dxos/effect": "0.8.4-main.84f28bd",
38
- "@dxos/functions": "0.8.4-main.84f28bd",
39
- "@dxos/graph": "0.8.4-main.84f28bd",
40
- "@dxos/invariant": "0.8.4-main.84f28bd",
41
- "@dxos/keys": "0.8.4-main.84f28bd",
42
- "@dxos/live-object": "0.8.4-main.84f28bd",
43
- "@dxos/log": "0.8.4-main.84f28bd",
44
- "@dxos/node-std": "0.8.4-main.84f28bd",
45
- "@dxos/schema": "0.8.4-main.84f28bd",
46
- "@dxos/util": "0.8.4-main.84f28bd"
50
+ "handlebars": "4.7.8",
51
+ "lodash.defaultsdeep": "^4.6.1",
52
+ "@dxos/ai": "0.8.4-main.a4bbb77",
53
+ "@dxos/async": "0.8.4-main.a4bbb77",
54
+ "@dxos/blueprints": "0.8.4-main.a4bbb77",
55
+ "@dxos/context": "0.8.4-main.a4bbb77",
56
+ "@dxos/debug": "0.8.4-main.a4bbb77",
57
+ "@dxos/echo": "0.8.4-main.a4bbb77",
58
+ "@dxos/echo-schema": "0.8.4-main.a4bbb77",
59
+ "@dxos/effect": "0.8.4-main.a4bbb77",
60
+ "@dxos/echo-db": "0.8.4-main.a4bbb77",
61
+ "@dxos/errors": "0.8.4-main.a4bbb77",
62
+ "@dxos/echo-protocol": "0.8.4-main.a4bbb77",
63
+ "@dxos/graph": "0.8.4-main.a4bbb77",
64
+ "@dxos/invariant": "0.8.4-main.a4bbb77",
65
+ "@dxos/functions": "0.8.4-main.a4bbb77",
66
+ "@dxos/keys": "0.8.4-main.a4bbb77",
67
+ "@dxos/live-object": "0.8.4-main.a4bbb77",
68
+ "@dxos/log": "0.8.4-main.a4bbb77",
69
+ "@dxos/node-std": "0.8.4-main.a4bbb77",
70
+ "@dxos/schema": "0.8.4-main.a4bbb77",
71
+ "@dxos/util": "0.8.4-main.a4bbb77"
47
72
  },
48
73
  "devDependencies": {
49
- "effect": "3.16.13",
74
+ "@types/lodash.defaultsdeep": "^4.6.6",
75
+ "effect": "3.18.3",
50
76
  "inquirer": "^12.0.0"
51
77
  },
52
78
  "peerDependencies": {
@@ -57,6 +83,6 @@
57
83
  },
58
84
  "beast": {},
59
85
  "scripts": {
60
- "run:chat": "tsx ./bin/chat.ts"
86
+ "run:chat": "vite-node ./bin/chat.ts"
61
87
  }
62
88
  }
@@ -0,0 +1,154 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { type ReadonlySignal, computed } from '@preact/signals-core';
6
+ import { Context, Schema } from 'effect';
7
+ import { Array, pipe } from 'effect';
8
+
9
+ import { Blueprint } from '@dxos/blueprints';
10
+ import { DXN, Obj, type Ref, type Relation, Type } from '@dxos/echo';
11
+ import { type Queue } from '@dxos/echo-db';
12
+ import { ComplexSet } from '@dxos/util';
13
+
14
+ /**
15
+ * Thread message that binds or unbinds contextual objects to a conversation.
16
+ */
17
+ // TODO(burdon): Move to @dxos/schema ContentBlock?
18
+ export const ContextBinding = Schema.Struct({
19
+ blueprints: Schema.Struct({
20
+ added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
21
+ removed: Schema.Array(Type.Ref(Blueprint.Blueprint)),
22
+ }),
23
+
24
+ // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)
25
+ objects: Schema.Struct({
26
+ added: Schema.Array(Type.Ref(Type.Expando)),
27
+ removed: Schema.Array(Type.Ref(Type.Expando)),
28
+ }),
29
+ }).pipe(
30
+ Type.Obj({
31
+ typename: 'dxos.org/type/ContextBinding',
32
+ version: '0.1.0',
33
+ }),
34
+ );
35
+
36
+ export interface ContextBinding extends Schema.Schema.Type<typeof ContextBinding> {}
37
+
38
+ export type BindingProps = Partial<{
39
+ blueprints: Ref.Ref<Blueprint.Blueprint>[];
40
+ objects: Ref.Ref<Type.Expando>[];
41
+ }>;
42
+
43
+ export class Bindings {
44
+ readonly blueprints = new ComplexSet<Ref.Ref<Blueprint.Blueprint>>((ref) => ref.dxn.toString());
45
+ // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
46
+ readonly objects = new ComplexSet<Ref.Ref<Type.Expando>>((ref) => ref.dxn.asEchoDXN()?.echoId);
47
+
48
+ toJSON() {
49
+ return {
50
+ blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
51
+ objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString()),
52
+ };
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Manages bindings of blueprints and objects to a conversation.
58
+ */
59
+ // TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?
60
+ export class AiContextBinder {
61
+ /**
62
+ * Reactive query of all bindings.
63
+ */
64
+ // TODO(burdon): Cache value?
65
+ readonly bindings: ReadonlySignal<Bindings> = computed(() => this._reduce(this._queue.objects));
66
+
67
+ readonly blueprints: ReadonlySignal<Ref.Ref<Blueprint.Blueprint>[]> = computed(() => [
68
+ ...this.bindings.value.blueprints,
69
+ ]);
70
+
71
+ readonly objects: ReadonlySignal<Ref.Ref<Type.Expando>[]> = computed(() => [...this.bindings.value.objects]);
72
+
73
+ constructor(private readonly _queue: Queue) {}
74
+
75
+ /**
76
+ * Asynchronous query of all bindings.
77
+ */
78
+ async query(): Promise<Bindings> {
79
+ const queueItems = await this._queue.queryObjects();
80
+ return this._reduce(queueItems);
81
+ }
82
+
83
+ // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
84
+ async bind(props: BindingProps): Promise<void> {
85
+ if (!props.blueprints?.length && !props.objects?.length) {
86
+ return;
87
+ }
88
+
89
+ const blueprints =
90
+ props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ??
91
+ [];
92
+ const objects =
93
+ props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
94
+
95
+ await this._queue.append([
96
+ Obj.make(ContextBinding, {
97
+ blueprints: {
98
+ added: blueprints,
99
+ removed: [],
100
+ },
101
+ objects: {
102
+ added: objects,
103
+ removed: [],
104
+ },
105
+ }),
106
+ ]);
107
+ }
108
+
109
+ async unbind(props: BindingProps): Promise<void> {
110
+ if (!props.blueprints?.length && !props.objects?.length) {
111
+ return;
112
+ }
113
+
114
+ await this._queue.append([
115
+ Obj.make(ContextBinding, {
116
+ blueprints: {
117
+ added: [],
118
+ removed: props.blueprints ?? [],
119
+ },
120
+ objects: {
121
+ added: [],
122
+ removed: props.objects ?? [],
123
+ },
124
+ }),
125
+ ]);
126
+ }
127
+
128
+ private _reduce(items: (Obj.Any | Relation.Any)[]): Bindings {
129
+ return pipe(
130
+ items,
131
+ Array.filter(Obj.instanceOf(ContextBinding)),
132
+ Array.reduce(new Bindings(), (context, item) => {
133
+ item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
134
+ item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
135
+ item.objects.removed.forEach((ref) => {
136
+ for (const obj of context.objects) {
137
+ if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
138
+ context.objects.delete(obj);
139
+ }
140
+ }
141
+ });
142
+ item.objects.added.forEach((ref) => context.objects.add(ref));
143
+ return context;
144
+ }),
145
+ );
146
+ }
147
+ }
148
+
149
+ export class AiContextService extends Context.Tag('@dxos/assistant/AiContextService')<
150
+ AiContextService,
151
+ {
152
+ binder: AiContextBinder;
153
+ }
154
+ >() {}
@@ -2,102 +2,118 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Message, type ExecutableTool } from '@dxos/ai';
6
- import { type ArtifactDefinition } from '@dxos/artifact';
7
- import { Event } from '@dxos/async';
8
- import { Obj, Ref } from '@dxos/echo';
5
+ import { type Toolkit } from '@effect/ai';
6
+ import { Array, Effect, Option } from 'effect';
7
+
8
+ import { Obj } from '@dxos/echo';
9
9
  import { type Queue } from '@dxos/echo-db';
10
- import { AiService, ToolResolverService, type ServiceContainer } from '@dxos/functions';
10
+ import { DatabaseService } from '@dxos/functions';
11
11
  import { log } from '@dxos/log';
12
- import { isNonNullable } from '@dxos/util';
13
-
14
- import { ContextBinder, type ContextBinding } from '../context';
15
- import { AISession, type SessionRunOptions } from '../session';
16
-
17
- export interface ConversationRunOptions {
18
- systemPrompt?: string;
19
- prompt: string;
12
+ import { DataType } from '@dxos/schema';
20
13
 
21
- tools?: ExecutableTool[];
22
- artifacts?: ArtifactDefinition[];
23
- extensions?: ToolContextExtensions;
24
- generationOptions?: SessionRunOptions['generationOptions'];
14
+ import {
15
+ AiSession,
16
+ type AiSessionRunError,
17
+ type AiSessionRunRequirements,
18
+ type GenerationObserver,
19
+ createToolkit,
20
+ } from '../session';
25
21
 
26
- /** @depreacated Should be managed by the conversation. */
27
- requiredArtifactIds?: string[];
22
+ import { AiContextBinder, AiContextService, type ContextBinding } from './context';
28
23
 
29
- // TODO(dmaretskyi): Move into conversation.
30
- artifactDiffResolver?: SessionRunOptions['artifactDiffResolver'];
24
+ export interface AiConversationRunParams {
25
+ prompt: string;
26
+ system?: string;
27
+ observer?: GenerationObserver;
31
28
  }
32
29
 
33
- export type ConversationOptions = {
34
- serviceContainer: ServiceContainer;
35
- queue: Queue<Message | ContextBinding>;
30
+ export type AiConversationOptions = {
31
+ queue: Queue<DataType.Message | ContextBinding>;
36
32
  };
37
33
 
38
34
  /**
39
- * Persistent conversation state.
40
- * Context + history + artifacts.
41
- * Backed by a Queue.
35
+ * Durable conversation state (initiated by users and agents) backed by a Queue.
36
+ * Executes tools based on AI responses and supports cancellation of in-progress requests.
42
37
  */
43
- export class Conversation {
44
- private readonly _serviceContainer: ServiceContainer;
45
- private readonly _queue: Queue<Message | ContextBinding>;
46
-
38
+ export class AiConversation {
47
39
  /**
48
- * Fired when the execution loop begins.
49
- * This is called before the first message is sent.
40
+ * Message and binding queue.
50
41
  */
51
- public readonly onBegin = new Event<AISession>();
42
+ private readonly _queue: Queue<DataType.Message | ContextBinding>;
52
43
 
53
44
  /**
54
45
  * Blueprints bound to the conversation.
55
46
  */
56
- public readonly context: ContextBinder;
47
+ private readonly _context: AiContextBinder;
57
48
 
58
- constructor(options: ConversationOptions) {
59
- this._serviceContainer = options.serviceContainer;
49
+ /**
50
+ * Toolkit from the current session request.
51
+ */
52
+ private _toolkit: Toolkit.WithHandler<any> | undefined;
53
+
54
+ public constructor(options: AiConversationOptions) {
60
55
  this._queue = options.queue;
61
- this.context = new ContextBinder(this._queue);
56
+ this._context = new AiContextBinder(this._queue);
57
+ }
58
+
59
+ public get context() {
60
+ return this._context;
62
61
  }
63
62
 
64
- async run(options: ConversationRunOptions): Promise<Message[]> {
65
- const session = new AISession({ operationModel: 'configured' });
66
- this.onBegin.emit(session);
67
-
68
- const history = await this.getHistory();
69
- const context = await this.context.query();
70
- const blueprints = (await Ref.Array.loadAll([...context.blueprints])).filter(isNonNullable);
71
- if (blueprints.length > 1) {
72
- log.warn('multiple blueprints are not yet supported');
73
- }
74
-
75
- const messages = await session.run({
76
- history,
77
- prompt: options.prompt,
78
- systemPrompt: (options.systemPrompt ?? '') + (blueprints.at(0)?.instructions ?? ''),
79
-
80
- // TODO(dmaretskyi): Artifacts come from the blueprint?
81
- artifacts: options.artifacts ?? [],
82
- tools: blueprints.at(0)?.tools ?? [],
83
- executableTools: options.tools,
84
- requiredArtifactIds: options.requiredArtifactIds,
85
- client: this._serviceContainer.getService(AiService).client,
86
- toolResolver: this._serviceContainer.getService(ToolResolverService).toolResolver,
87
- extensions: {
88
- serviceContainer: this._serviceContainer,
89
- ...options.extensions,
90
- },
91
- generationOptions: options.generationOptions,
92
- });
93
-
94
- await this._queue.append(messages);
95
-
96
- return messages;
63
+ public get toolkit() {
64
+ return this._toolkit;
97
65
  }
98
66
 
99
- async getHistory(): Promise<Message[]> {
67
+ public async getHistory(): Promise<DataType.Message[]> {
100
68
  const queueItems = await this._queue.queryObjects();
101
- return queueItems.filter(Obj.instanceOf(Message));
69
+ return queueItems.filter(Obj.instanceOf(DataType.Message));
70
+ }
71
+
72
+ /**
73
+ * Creates a new cancelable request effect.
74
+ */
75
+ createRequest(
76
+ params: AiConversationRunParams,
77
+ ): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> {
78
+ return Effect.gen(this, function* () {
79
+ const session = new AiSession();
80
+ const history = yield* Effect.promise(() => this.getHistory());
81
+
82
+ // Get context objects.
83
+ const context = yield* Effect.promise(() => this.context.query());
84
+ const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(
85
+ Effect.map(Array.filter(Option.isSome)),
86
+ Effect.map(Array.map((option) => option.value)),
87
+ );
88
+ const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(
89
+ Effect.map(Array.filter(Option.isSome)),
90
+ Effect.map(Array.map((option) => option.value)),
91
+ );
92
+
93
+ // Create toolkit.
94
+ const toolkit = yield* createToolkit({ blueprints });
95
+ this._toolkit = toolkit;
96
+
97
+ const start = Date.now();
98
+ log('run', {
99
+ history: history.length,
100
+ blueprints: blueprints.length,
101
+ objects: objects.length,
102
+ tools: this._toolkit?.tools.length ?? 0,
103
+ });
104
+
105
+ // Process request.
106
+ const messages = yield* session.run({ history, blueprints, objects, toolkit, ...params }).pipe(
107
+ Effect.provideService(AiContextService, {
108
+ binder: this.context,
109
+ }),
110
+ );
111
+
112
+ log('result', { messages: messages.length, duration: Date.now() - start });
113
+
114
+ // Append to queue.
115
+ yield* Effect.promise(() => this._queue.append(messages));
116
+ return messages;
117
+ }).pipe(Effect.withSpan('AiConversation.request'));
102
118
  }
103
119
  }
@@ -2,4 +2,5 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ export * from './context';
5
6
  export * from './conversation';
@@ -0,0 +1,43 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { createDocAccessor } from '@dxos/echo-db';
8
+ import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
+ import { DataType } from '@dxos/schema';
10
+ import { trim } from '@dxos/util';
11
+
12
+ import { applyDiffs } from './diff';
13
+
14
+ describe('diff', () => {
15
+ it('should apply diffs', async () => {
16
+ const builder = new EchoTestBuilder();
17
+ const { db, graph } = await builder.createDatabase();
18
+ graph.schemaRegistry.addSchema([DataType.Text]);
19
+
20
+ const document = trim`
21
+ # Hello World
22
+ There'z a typo in this sentence.
23
+ And another oon here.
24
+ But not this one.
25
+ `;
26
+
27
+ const text = db.add(DataType.makeText(document));
28
+ const accessor = createDocAccessor(text, ['content']);
29
+ const result = applyDiffs(accessor, [
30
+ `- There'z a typo in this sentence.`,
31
+ `+ There is a typo in this sentence.`,
32
+ `- And another oon here.`,
33
+ `+ And another one here.`,
34
+ ]);
35
+
36
+ expect(result).toBe(trim`
37
+ # Hello World
38
+ There is a typo in this sentence.
39
+ And another one here.
40
+ But not this one.
41
+ `);
42
+ });
43
+ });
package/src/diff.ts ADDED
@@ -0,0 +1,79 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { next as A, type Doc } from '@automerge/automerge';
6
+
7
+ import { DocAccessor, toCursorRange } from '@dxos/echo-db';
8
+ import { log } from '@dxos/log';
9
+ import { isNonNullable } from '@dxos/util';
10
+
11
+ // Relevant info:
12
+ // https://github.com/Minahil-official/GPT-4.1-Promting-Guide?tab=readme-ov-file#-apply-patch-tool-format-v4a-diff
13
+
14
+ // TOOD(burdon): Support append to end (no "-").
15
+
16
+ export type Diff = {
17
+ match: string;
18
+ replace: string;
19
+ };
20
+
21
+ /**
22
+ * Convert a list of diffs into a list of operations.
23
+ */
24
+ export const reduceDiffs = (diffs: readonly string[]): Diff[] => {
25
+ return diffs.reduce<Diff[]>((acc, diff) => {
26
+ const current = acc[acc.length - 1];
27
+ const [op, ...rest] = diff.split(' ');
28
+ switch (op) {
29
+ case '-': {
30
+ if (current && !current.match) {
31
+ current.match += rest.join(' ');
32
+ } else {
33
+ acc.push({ match: rest.join(' '), replace: '' });
34
+ }
35
+ return acc;
36
+ }
37
+ case '+': {
38
+ if (current && !current.replace) {
39
+ current.replace += rest.join(' ');
40
+ } else {
41
+ acc.push({ match: '', replace: rest.join(' ') });
42
+ }
43
+ return acc;
44
+ }
45
+ }
46
+
47
+ return acc;
48
+ }, []);
49
+ };
50
+
51
+ export const computeDiffsWithCursors = <T>(accessor: DocAccessor<T>, diffs: readonly string[]) => {
52
+ return reduceDiffs(diffs)
53
+ .map((diff) => {
54
+ const text = DocAccessor.getValue<string>(accessor);
55
+ const idx = text.indexOf(diff.match);
56
+ if (idx !== -1) {
57
+ return { cursor: toCursorRange(accessor, idx, idx + diff.match.length), text: diff.replace };
58
+ }
59
+ })
60
+ .filter(isNonNullable);
61
+ };
62
+
63
+ export const applyDiffs = <T>(accessor: DocAccessor<T>, diffs: readonly string[]): string => {
64
+ for (const diff of reduceDiffs(diffs)) {
65
+ accessor.handle.change((doc: Doc<T>) => {
66
+ const text = DocAccessor.getValue<string>(accessor);
67
+ const idx = text.indexOf(diff.match);
68
+ if (idx !== -1) {
69
+ // TODO(burdon): Replace smallest substring.
70
+ // NOTE: This only replaces the first match.
71
+ A.splice(doc, accessor.path as A.Prop[], idx, diff.match.length, diff.replace);
72
+ } else {
73
+ log.warn('diff not found', diff);
74
+ }
75
+ });
76
+ }
77
+
78
+ return DocAccessor.getValue<string>(accessor);
79
+ };
package/src/errors.ts ADDED
@@ -0,0 +1,15 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { BaseError } from '@dxos/errors';
6
+
7
+ /**
8
+ * Generic error from AI model.
9
+ */
10
+ export class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}
11
+
12
+ /**
13
+ * Generic error for AI agent execution.
14
+ */
15
+ export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}