@dxos/assistant 0.8.4-main.f9ba587 → 0.8.4-main.fffef41

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 (177) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +7 -0
  3. package/dist/lib/browser/extraction/index.mjs +225 -0
  4. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +1114 -1843
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  9. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  10. package/dist/lib/node-esm/extraction/index.mjs +226 -0
  11. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  12. package/dist/lib/node-esm/index.mjs +1114 -1844
  13. package/dist/lib/node-esm/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/types/src/conversation/context.d.ts +103 -0
  16. package/dist/types/src/conversation/context.d.ts.map +1 -0
  17. package/dist/types/src/conversation/conversation.d.ts +29 -32
  18. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  19. package/dist/types/src/conversation/index.d.ts +1 -0
  20. package/dist/types/src/conversation/index.d.ts.map +1 -1
  21. package/dist/types/src/diff.d.ts +15 -0
  22. package/dist/types/src/diff.d.ts.map +1 -0
  23. package/dist/types/src/diff.test.d.ts +2 -0
  24. package/dist/types/src/diff.test.d.ts.map +1 -0
  25. package/dist/types/src/errors.d.ts +71 -0
  26. package/dist/types/src/errors.d.ts.map +1 -0
  27. package/dist/types/src/execution-graph.d.ts +85 -0
  28. package/dist/types/src/execution-graph.d.ts.map +1 -0
  29. package/dist/types/src/execution-graph.test.d.ts +2 -0
  30. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  31. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  32. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  33. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +195 -58
  34. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  35. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  36. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  37. package/dist/types/src/extraction/extraction.d.ts +264 -165
  38. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  39. package/dist/types/src/extraction/quotes.d.ts +1 -1
  40. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  41. package/dist/types/src/functions/index.d.ts +2 -0
  42. package/dist/types/src/functions/index.d.ts.map +1 -0
  43. package/dist/types/src/functions/services.d.ts +20 -0
  44. package/dist/types/src/functions/services.d.ts.map +1 -0
  45. package/dist/types/src/index.d.ts +5 -5
  46. package/dist/types/src/index.d.ts.map +1 -1
  47. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  48. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  49. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  50. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  51. package/dist/types/src/session/error-handling.d.ts +4 -0
  52. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  53. package/dist/types/src/session/format.d.ts +12 -0
  54. package/dist/types/src/session/format.d.ts.map +1 -0
  55. package/dist/types/src/session/format.test.d.ts +2 -0
  56. package/dist/types/src/session/format.test.d.ts.map +1 -0
  57. package/dist/types/src/session/index.d.ts +4 -0
  58. package/dist/types/src/session/index.d.ts.map +1 -1
  59. package/dist/types/src/session/observer.d.ts +22 -0
  60. package/dist/types/src/session/observer.d.ts.map +1 -0
  61. package/dist/types/src/session/session.d.ts +36 -268
  62. package/dist/types/src/session/session.d.ts.map +1 -1
  63. package/dist/types/src/session/toolkit.d.ts +15 -0
  64. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  65. package/dist/types/src/session/version-pin.d.ts +5 -5
  66. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  67. package/dist/types/src/templates/index.d.ts +2 -0
  68. package/dist/types/src/templates/index.d.ts.map +1 -0
  69. package/dist/types/src/templates/system.d.ts +18 -0
  70. package/dist/types/src/templates/system.d.ts.map +1 -0
  71. package/dist/types/src/types/artifact.d.ts +20 -0
  72. package/dist/types/src/types/artifact.d.ts.map +1 -0
  73. package/dist/types/src/types/index.d.ts +2 -0
  74. package/dist/types/src/types/index.d.ts.map +1 -0
  75. package/dist/types/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +48 -26
  77. package/src/conversation/context.ts +186 -0
  78. package/src/conversation/conversation.ts +101 -76
  79. package/src/conversation/index.ts +1 -0
  80. package/src/diff.test.ts +43 -0
  81. package/src/diff.ts +84 -0
  82. package/src/errors.ts +15 -0
  83. package/src/execution-graph.test.ts +740 -0
  84. package/src/execution-graph.ts +509 -0
  85. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +14 -25
  86. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +48 -52
  87. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +18 -17
  88. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +43 -41
  89. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  90. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
  91. package/src/extraction/extraction.ts +7 -6
  92. package/src/extraction/quotes.test.ts +3 -3
  93. package/src/extraction/quotes.ts +4 -4
  94. package/src/functions/index.ts +5 -0
  95. package/src/functions/services.ts +162 -0
  96. package/src/index.ts +5 -5
  97. package/src/session/GenericToolkit.ts +130 -0
  98. package/src/session/artifact-diff.ts +41 -0
  99. package/src/session/error-handling.ts +41 -0
  100. package/src/session/format.test.ts +61 -0
  101. package/src/session/format.ts +144 -0
  102. package/src/session/index.ts +5 -0
  103. package/src/session/observer.ts +59 -0
  104. package/src/session/session.conversations.json +1 -0
  105. package/src/session/session.test.ts +88 -214
  106. package/src/session/session.ts +170 -539
  107. package/src/session/toolkit.ts +48 -0
  108. package/src/session/version-pin.ts +11 -12
  109. package/src/templates/index.ts +5 -0
  110. package/src/templates/instructions/format.tpl +61 -0
  111. package/src/templates/instructions/system.tpl +48 -0
  112. package/src/templates/system.ts +41 -0
  113. package/src/types/artifact.ts +71 -0
  114. package/src/types/index.ts +5 -0
  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/summarization/summarization.test.d.ts +0 -2
  145. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  146. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  147. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  148. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  149. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  150. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  151. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  152. package/dist/types/src/testing/index.d.ts +0 -3
  153. package/dist/types/src/testing/index.d.ts.map +0 -1
  154. package/dist/types/src/types.d.ts +0 -3
  155. package/dist/types/src/types.d.ts.map +0 -1
  156. package/src/blueprint/blueprint.ts +0 -75
  157. package/src/blueprint/index.ts +0 -6
  158. package/src/blueprint/registry.ts +0 -15
  159. package/src/context/binder.ts +0 -101
  160. package/src/context/binding.ts +0 -31
  161. package/src/context/index.ts +0 -6
  162. package/src/research/exa.ts +0 -100
  163. package/src/research/graph.test.ts +0 -15
  164. package/src/research/graph.ts +0 -337
  165. package/src/research/index.ts +0 -7
  166. package/src/research/instructions-research.tpl +0 -97
  167. package/src/research/research.test.ts +0 -190
  168. package/src/research/research.ts +0 -90
  169. package/src/session/version-pin.test.ts +0 -26
  170. package/src/summarization/summarization.test.ts +0 -221
  171. package/src/testing/exa-search-1748337321991.ts +0 -131
  172. package/src/testing/exa-search-1748337331526.ts +0 -144
  173. package/src/testing/exa-search-1748337344119.ts +0 -133
  174. package/src/testing/index.ts +0 -11
  175. package/src/typedefs.d.ts +0 -8
  176. package/src/types.ts +0 -8
  177. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/assistant",
3
- "version": "0.8.4-main.f9ba587",
3
+ "version": "0.8.4-main.fffef41",
4
4
  "description": "Natural language interface to DXOS",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -10,44 +10,66 @@
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/experimental": "0.56.0",
44
+ "@effect/platform": "^0.92.1",
45
+ "@preact/signals-core": "^1.12.1",
25
46
  "@xenova/transformers": "^2.17.2",
26
- "chalk": "^4.1.0",
27
- "exa-js": "^1.5.12",
28
- "@dxos/ai": "0.8.4-main.f9ba587",
29
- "@dxos/artifact": "0.8.4-main.f9ba587",
30
- "@dxos/async": "0.8.4-main.f9ba587",
31
- "@dxos/context": "0.8.4-main.f9ba587",
32
- "@dxos/debug": "0.8.4-main.f9ba587",
33
- "@dxos/echo-db": "0.8.4-main.f9ba587",
34
- "@dxos/echo-protocol": "0.8.4-main.f9ba587",
35
- "@dxos/echo-schema": "0.8.4-main.f9ba587",
36
- "@dxos/effect": "0.8.4-main.f9ba587",
37
- "@dxos/graph": "0.8.4-main.f9ba587",
38
- "@dxos/functions": "0.8.4-main.f9ba587",
39
- "@dxos/echo": "0.8.4-main.f9ba587",
40
- "@dxos/invariant": "0.8.4-main.f9ba587",
41
- "@dxos/live-object": "0.8.4-main.f9ba587",
42
- "@dxos/keys": "0.8.4-main.f9ba587",
43
- "@dxos/log": "0.8.4-main.f9ba587",
44
- "@dxos/schema": "0.8.4-main.f9ba587",
45
- "@dxos/node-std": "0.8.4-main.f9ba587",
46
- "@dxos/util": "0.8.4-main.f9ba587"
47
+ "lodash.defaultsdeep": "^4.6.1",
48
+ "@dxos/ai": "0.8.4-main.fffef41",
49
+ "@dxos/async": "0.8.4-main.fffef41",
50
+ "@dxos/blueprints": "0.8.4-main.fffef41",
51
+ "@dxos/echo": "0.8.4-main.fffef41",
52
+ "@dxos/debug": "0.8.4-main.fffef41",
53
+ "@dxos/echo-db": "0.8.4-main.fffef41",
54
+ "@dxos/echo-protocol": "0.8.4-main.fffef41",
55
+ "@dxos/context": "0.8.4-main.fffef41",
56
+ "@dxos/effect": "0.8.4-main.fffef41",
57
+ "@dxos/errors": "0.8.4-main.fffef41",
58
+ "@dxos/functions": "0.8.4-main.fffef41",
59
+ "@dxos/functions-runtime": "0.8.4-main.fffef41",
60
+ "@dxos/graph": "0.8.4-main.fffef41",
61
+ "@dxos/invariant": "0.8.4-main.fffef41",
62
+ "@dxos/keys": "0.8.4-main.fffef41",
63
+ "@dxos/live-object": "0.8.4-main.fffef41",
64
+ "@dxos/node-std": "0.8.4-main.fffef41",
65
+ "@dxos/schema": "0.8.4-main.fffef41",
66
+ "@dxos/log": "0.8.4-main.fffef41",
67
+ "@dxos/types": "0.8.4-main.fffef41",
68
+ "@dxos/util": "0.8.4-main.fffef41"
47
69
  },
48
70
  "devDependencies": {
49
- "effect": "3.16.13",
50
- "inquirer": "^12.0.0"
71
+ "@types/lodash.defaultsdeep": "^4.6.6",
72
+ "effect": "3.18.3"
51
73
  },
52
74
  "peerDependencies": {
53
75
  "effect": "^3.13.3"
@@ -57,6 +79,6 @@
57
79
  },
58
80
  "beast": {},
59
81
  "scripts": {
60
- "run:chat": "tsx ./bin/chat.ts"
82
+ "run:chat": "vite-node ./bin/chat.ts"
61
83
  }
62
84
  }
@@ -0,0 +1,186 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { type ReadonlySignal, computed } from '@preact/signals-core';
6
+ import * as Array from 'effect/Array';
7
+ import * as Context from 'effect/Context';
8
+ import * as Function from 'effect/Function';
9
+ import * as Schema from 'effect/Schema';
10
+
11
+ import { Blueprint } from '@dxos/blueprints';
12
+ import { Resource } from '@dxos/context';
13
+ import { DXN, Filter, Obj, Query, type Ref, type Relation, Type } from '@dxos/echo';
14
+ import { type Queue } from '@dxos/echo-db';
15
+ import { invariant } from '@dxos/invariant';
16
+ import { ComplexSet } from '@dxos/util';
17
+
18
+ /**
19
+ * Thread message that binds or unbinds contextual objects to a conversation.
20
+ */
21
+ // TODO(burdon): Move to @dxos/schema ContentBlock?
22
+ export const ContextBinding = Schema.Struct({
23
+ blueprints: Schema.Struct({
24
+ added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
25
+ removed: Schema.Array(Type.Ref(Blueprint.Blueprint)),
26
+ }),
27
+
28
+ // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)
29
+ objects: Schema.Struct({
30
+ added: Schema.Array(Type.Ref(Type.Expando)),
31
+ removed: Schema.Array(Type.Ref(Type.Expando)),
32
+ }),
33
+ }).pipe(
34
+ Type.Obj({
35
+ typename: 'dxos.org/type/ContextBinding',
36
+ version: '0.1.0',
37
+ }),
38
+ );
39
+
40
+ export interface ContextBinding extends Schema.Schema.Type<typeof ContextBinding> {}
41
+
42
+ export type BindingProps = Partial<{
43
+ blueprints: Ref.Ref<Blueprint.Blueprint>[];
44
+ objects: Ref.Ref<Type.Expando>[];
45
+ }>;
46
+
47
+ export class Bindings {
48
+ readonly blueprints = new ComplexSet<Ref.Ref<Blueprint.Blueprint>>((ref) => ref.dxn.toString());
49
+ // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
50
+ readonly objects = new ComplexSet<Ref.Ref<Type.Expando>>((ref) => ref.dxn.asEchoDXN()?.echoId);
51
+
52
+ toJSON() {
53
+ return {
54
+ blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
55
+ objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString()),
56
+ };
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Manages bindings of blueprints and objects to a conversation.
62
+ */
63
+ // TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?
64
+ export class AiContextBinder extends Resource {
65
+ /**
66
+ * Reactive query of all bindings.
67
+ */
68
+ // TODO(burdon): Cache value?
69
+ private _bindings?: ReadonlySignal<Bindings>;
70
+ private _blueprints?: ReadonlySignal<Ref.Ref<Blueprint.Blueprint>[]>;
71
+ private _objects?: ReadonlySignal<Ref.Ref<Type.Expando>[]>;
72
+
73
+ constructor(private readonly _queue: Queue) {
74
+ super();
75
+ }
76
+
77
+ get bindings() {
78
+ invariant(this._bindings, 'AiContextBinder not open');
79
+ return this._bindings;
80
+ }
81
+
82
+ get blueprints() {
83
+ invariant(this._blueprints, 'AiContextBinder not open');
84
+ return this._blueprints;
85
+ }
86
+
87
+ get objects() {
88
+ invariant(this._objects, 'AiContextBinder not open');
89
+ return this._objects;
90
+ }
91
+
92
+ // TODO(wittjosiah): Use parent context?
93
+ protected override async _open(): Promise<void> {
94
+ const query = this._queue.query(Query.select(Filter.everything()));
95
+ this._ctx.onDispose(query.subscribe(() => {}));
96
+ this._bindings = computed(() => this._reduce(query.objects));
97
+ this._blueprints = computed(() => [...this.bindings.value.blueprints]);
98
+ this._objects = computed(() => [...this.bindings.value.objects]);
99
+ }
100
+
101
+ protected override async _close(): Promise<void> {
102
+ this._bindings = undefined;
103
+ this._blueprints = undefined;
104
+ this._objects = undefined;
105
+ }
106
+
107
+ /**
108
+ * Asynchronous query of all bindings.
109
+ */
110
+ async query(): Promise<Bindings> {
111
+ const { objects } = await this._queue.query(Query.select(Filter.everything())).run();
112
+ return this._reduce(objects);
113
+ }
114
+
115
+ // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
116
+ async bind(props: BindingProps): Promise<void> {
117
+ const blueprints =
118
+ props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ??
119
+ [];
120
+ const objects =
121
+ props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
122
+
123
+ if (!blueprints.length && !objects.length) {
124
+ return;
125
+ }
126
+
127
+ await this._queue.append([
128
+ Obj.make(ContextBinding, {
129
+ blueprints: {
130
+ added: blueprints,
131
+ removed: [],
132
+ },
133
+ objects: {
134
+ added: objects,
135
+ removed: [],
136
+ },
137
+ }),
138
+ ]);
139
+ }
140
+
141
+ async unbind(props: BindingProps): Promise<void> {
142
+ if (!props.blueprints?.length && !props.objects?.length) {
143
+ return;
144
+ }
145
+
146
+ await this._queue.append([
147
+ Obj.make(ContextBinding, {
148
+ blueprints: {
149
+ added: [],
150
+ removed: props.blueprints ?? [],
151
+ },
152
+ objects: {
153
+ added: [],
154
+ removed: props.objects ?? [],
155
+ },
156
+ }),
157
+ ]);
158
+ }
159
+
160
+ private _reduce(items: (Obj.Any | Relation.Any)[]): Bindings {
161
+ return Function.pipe(
162
+ items,
163
+ Array.filter(Obj.instanceOf(ContextBinding)),
164
+ Array.reduce(new Bindings(), (context, item) => {
165
+ item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
166
+ item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
167
+ item.objects.removed.forEach((ref) => {
168
+ for (const obj of context.objects) {
169
+ if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
170
+ context.objects.delete(obj);
171
+ }
172
+ }
173
+ });
174
+ item.objects.added.forEach((ref) => context.objects.add(ref));
175
+ return context;
176
+ }),
177
+ );
178
+ }
179
+ }
180
+
181
+ export class AiContextService extends Context.Tag('@dxos/assistant/AiContextService')<
182
+ AiContextService,
183
+ {
184
+ binder: AiContextBinder;
185
+ }
186
+ >() {}
@@ -2,102 +2,127 @@
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 * as Toolkit from '@effect/ai/Toolkit';
6
+ import * as Array from 'effect/Array';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Option from 'effect/Option';
9
+
10
+ import { Resource } from '@dxos/context';
11
+ import { Obj } from '@dxos/echo';
9
12
  import { type Queue } from '@dxos/echo-db';
10
- import { AiService, ToolResolverService, type ServiceContainer } from '@dxos/functions';
13
+ import { DatabaseService } from '@dxos/echo-db';
11
14
  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';
15
+ import { Message } from '@dxos/types';
16
16
 
17
- export interface ConversationRunOptions {
18
- systemPrompt?: string;
19
- prompt: string;
17
+ import {
18
+ AiSession,
19
+ type AiSessionRunError,
20
+ type AiSessionRunRequirements,
21
+ type GenerationObserver,
22
+ createToolkit,
23
+ } from '../session';
20
24
 
21
- tools?: ExecutableTool[];
22
- artifacts?: ArtifactDefinition[];
23
- extensions?: ToolContextExtensions;
24
- generationOptions?: SessionRunOptions['generationOptions'];
25
+ import { AiContextBinder, AiContextService, type ContextBinding } from './context';
25
26
 
26
- /** @depreacated Should be managed by the conversation. */
27
- requiredArtifactIds?: string[];
28
-
29
- // TODO(dmaretskyi): Move into conversation.
30
- artifactDiffResolver?: SessionRunOptions['artifactDiffResolver'];
27
+ export interface AiConversationRunParams {
28
+ prompt: string;
29
+ system?: string;
30
+ observer?: GenerationObserver;
31
31
  }
32
32
 
33
- export type ConversationOptions = {
34
- serviceContainer: ServiceContainer;
35
- queue: Queue<Message | ContextBinding>;
36
- };
37
-
38
33
  /**
39
- * Persistent conversation state.
40
- * Context + history + artifacts.
41
- * Backed by a Queue.
34
+ * Durable conversation state (initiated by users and agents) backed by a Queue.
35
+ * Executes tools based on AI responses and supports cancellation of in-progress requests.
42
36
  */
43
- export class Conversation {
44
- private readonly _serviceContainer: ServiceContainer;
45
- private readonly _queue: Queue<Message | ContextBinding>;
46
-
37
+ export class AiConversation extends Resource {
47
38
  /**
48
- * Fired when the execution loop begins.
49
- * This is called before the first message is sent.
39
+ * Message and binding queue.
50
40
  */
51
- public readonly onBegin = new Event<AISession>();
41
+ private readonly _queue: Queue<Message.Message | ContextBinding>;
52
42
 
53
43
  /**
54
44
  * Blueprints bound to the conversation.
55
45
  */
56
- public readonly context: ContextBinder;
46
+ private readonly _context: AiContextBinder;
47
+
48
+ /**
49
+ * Toolkit from the current session request.
50
+ */
51
+ private _toolkit: Toolkit.WithHandler<any> | undefined;
57
52
 
58
- constructor(options: ConversationOptions) {
59
- this._serviceContainer = options.serviceContainer;
60
- this._queue = options.queue;
61
- this.context = new ContextBinder(this._queue);
53
+ public constructor(queue: Queue<Message.Message | ContextBinding>) {
54
+ super();
55
+ this._queue = queue;
56
+ this._context = new AiContextBinder(this._queue);
62
57
  }
63
58
 
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;
59
+ protected override async _open(): Promise<void> {
60
+ // TODO(wittjosiah): Pass in parent context?
61
+ await this._context.open();
97
62
  }
98
63
 
99
- async getHistory(): Promise<Message[]> {
64
+ protected override async _close(): Promise<void> {
65
+ await this._context.close();
66
+ }
67
+
68
+ public get context() {
69
+ return this._context;
70
+ }
71
+
72
+ public get toolkit() {
73
+ return this._toolkit;
74
+ }
75
+
76
+ public async getHistory(): Promise<Message.Message[]> {
100
77
  const queueItems = await this._queue.queryObjects();
101
- return queueItems.filter(Obj.instanceOf(Message));
78
+ return queueItems.filter(Obj.instanceOf(Message.Message));
79
+ }
80
+
81
+ /**
82
+ * Creates a new cancelable request effect.
83
+ */
84
+ createRequest(
85
+ params: AiConversationRunParams,
86
+ ): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> {
87
+ return Effect.gen(this, function* () {
88
+ const session = new AiSession();
89
+ const history = yield* Effect.promise(() => this.getHistory());
90
+
91
+ // Get context objects.
92
+ const context = yield* Effect.promise(() => this.context.query());
93
+ const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(
94
+ Effect.map(Array.filter(Option.isSome)),
95
+ Effect.map(Array.map((option) => option.value)),
96
+ );
97
+ const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(
98
+ Effect.map(Array.filter(Option.isSome)),
99
+ Effect.map(Array.map((option) => option.value)),
100
+ );
101
+
102
+ // Create toolkit.
103
+ const toolkit = yield* createToolkit({ blueprints });
104
+ this._toolkit = toolkit;
105
+
106
+ const start = Date.now();
107
+ log('run', {
108
+ history: history.length,
109
+ blueprints: blueprints.length,
110
+ objects: objects.length,
111
+ tools: this._toolkit?.tools.length ?? 0,
112
+ });
113
+
114
+ // Process request.
115
+ const messages = yield* session.run({ history, blueprints, objects, toolkit, ...params }).pipe(
116
+ Effect.provideService(AiContextService, {
117
+ binder: this.context,
118
+ }),
119
+ );
120
+
121
+ log('result', { messages: messages.length, duration: Date.now() - start });
122
+
123
+ // Append to queue.
124
+ yield* Effect.promise(() => this._queue.append(messages));
125
+ return messages;
126
+ }).pipe(Effect.withSpan('AiConversation.request'));
102
127
  }
103
128
  }
@@ -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 { Text } 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([Text.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(Text.make(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,84 @@
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
+ // TODO(burdon): Anthropic only.
15
+ // https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool#example-str-replace-command
16
+ // AI_TOOL_NOT_FOUND: str_replace_based_edit_tool
17
+ // 'str_replace_based_edit_tool',
18
+
19
+ // TOOD(burdon): Support append to end (no "-").
20
+
21
+ export type Diff = {
22
+ match: string;
23
+ replace: string;
24
+ };
25
+
26
+ /**
27
+ * Convert a list of diffs into a list of operations.
28
+ */
29
+ export const reduceDiffs = (diffs: readonly string[]): Diff[] => {
30
+ return diffs.reduce<Diff[]>((acc, diff) => {
31
+ const current = acc[acc.length - 1];
32
+ const [op, ...rest] = diff.split(' ');
33
+ switch (op) {
34
+ case '-': {
35
+ if (current && !current.match) {
36
+ current.match += rest.join(' ');
37
+ } else {
38
+ acc.push({ match: rest.join(' '), replace: '' });
39
+ }
40
+ return acc;
41
+ }
42
+ case '+': {
43
+ if (current && !current.replace) {
44
+ current.replace += rest.join(' ');
45
+ } else {
46
+ acc.push({ match: '', replace: rest.join(' ') });
47
+ }
48
+ return acc;
49
+ }
50
+ }
51
+
52
+ return acc;
53
+ }, []);
54
+ };
55
+
56
+ export const computeDiffsWithCursors = <T>(accessor: DocAccessor<T>, diffs: readonly string[]) => {
57
+ return reduceDiffs(diffs)
58
+ .map((diff) => {
59
+ const text = DocAccessor.getValue<string>(accessor);
60
+ const idx = text.indexOf(diff.match);
61
+ if (idx !== -1) {
62
+ return { cursor: toCursorRange(accessor, idx, idx + diff.match.length), text: diff.replace };
63
+ }
64
+ })
65
+ .filter(isNonNullable);
66
+ };
67
+
68
+ export const applyDiffs = <T>(accessor: DocAccessor<T>, diffs: readonly string[]): string => {
69
+ for (const diff of reduceDiffs(diffs)) {
70
+ accessor.handle.change((doc: Doc<T>) => {
71
+ const text = DocAccessor.getValue<string>(accessor);
72
+ const idx = text.indexOf(diff.match);
73
+ if (idx !== -1) {
74
+ // TODO(burdon): Replace smallest substring.
75
+ // NOTE: This only replaces the first match.
76
+ A.splice(doc, accessor.path as A.Prop[], idx, diff.match.length, diff.replace);
77
+ } else {
78
+ log.warn('diff not found', diff);
79
+ }
80
+ });
81
+ }
82
+
83
+ return DocAccessor.getValue<string>(accessor);
84
+ };
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') {}