@dxos/assistant 0.8.4-main.b97322e → 0.8.4-main.c4373fc

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 (164) hide show
  1. package/dist/lib/browser/chunk-CWGVG235.mjs +380 -0
  2. package/dist/lib/browser/chunk-CWGVG235.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 +687 -1649
  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-OV5PMQPB.mjs +382 -0
  15. package/dist/lib/node-esm/chunk-OV5PMQPB.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 +686 -1649
  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 +97 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +25 -22
  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 +46 -9
  34. package/dist/types/src/errors.d.ts.map +1 -1
  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 +103 -64
  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.map +1 -1
  44. package/dist/types/src/extraction/extraction.d.ts +252 -218
  45. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  46. package/dist/types/src/extraction/quotes.d.ts +1 -1
  47. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  48. package/dist/types/src/functions/services.d.ts +17 -4
  49. package/dist/types/src/functions/services.d.ts.map +1 -1
  50. package/dist/types/src/index.d.ts +3 -3
  51. package/dist/types/src/index.d.ts.map +1 -1
  52. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  53. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  54. package/dist/types/src/session/error-handling.d.ts +4 -0
  55. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  56. package/dist/types/src/session/format.d.ts +184 -0
  57. package/dist/types/src/session/format.d.ts.map +1 -0
  58. package/dist/types/src/session/format.test.d.ts +2 -0
  59. package/dist/types/src/session/format.test.d.ts.map +1 -0
  60. package/dist/types/src/session/index.d.ts +3 -0
  61. package/dist/types/src/session/index.d.ts.map +1 -1
  62. package/dist/types/src/session/observer.d.ts +22 -0
  63. package/dist/types/src/session/observer.d.ts.map +1 -0
  64. package/dist/types/src/session/session.d.ts +27 -236
  65. package/dist/types/src/session/session.d.ts.map +1 -1
  66. package/dist/types/src/session/toolkit.d.ts +15 -0
  67. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  68. package/dist/types/src/session/version-pin.d.ts +3 -3
  69. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  70. package/dist/types/src/templates/index.d.ts +1 -1
  71. package/dist/types/src/templates/system.d.ts +18 -0
  72. package/dist/types/src/templates/system.d.ts.map +1 -0
  73. package/dist/types/src/types.d.ts +5 -2
  74. package/dist/types/src/types.d.ts.map +1 -1
  75. package/dist/types/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +44 -32
  77. package/src/conversation/context.ts +156 -0
  78. package/src/conversation/conversation.ts +78 -53
  79. package/src/conversation/index.ts +1 -0
  80. package/src/diff.test.ts +43 -0
  81. package/src/diff.ts +79 -0
  82. package/src/errors.ts +6 -1
  83. package/src/execution-graph.test.ts +738 -0
  84. package/src/execution-graph.ts +500 -0
  85. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +8 -7
  86. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +13 -11
  87. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
  88. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +15 -8
  89. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -1
  90. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  91. package/src/extraction/extraction.ts +2 -2
  92. package/src/extraction/quotes.test.ts +3 -3
  93. package/src/extraction/quotes.ts +4 -4
  94. package/src/functions/services.ts +114 -95
  95. package/src/index.ts +3 -3
  96. package/src/session/artifact-diff.ts +41 -0
  97. package/src/session/error-handling.ts +41 -0
  98. package/src/session/format.test.ts +60 -0
  99. package/src/session/format.ts +142 -0
  100. package/src/session/index.ts +3 -0
  101. package/src/session/observer.ts +59 -0
  102. package/src/session/session.conversations.json +1 -0
  103. package/src/session/session.test.ts +37 -198
  104. package/src/session/session.ts +125 -249
  105. package/src/session/toolkit.ts +48 -0
  106. package/src/session/version-pin.ts +5 -5
  107. package/src/summarization/summarization.test.ts +16 -22
  108. package/src/templates/format.tpl +60 -0
  109. package/src/templates/index.ts +1 -1
  110. package/src/templates/system.tpl +48 -0
  111. package/src/templates/system.ts +41 -0
  112. package/src/types.ts +12 -7
  113. package/src/typings.d.ts +5 -0
  114. package/dist/types/bin/chat.d.ts +0 -2
  115. package/dist/types/bin/chat.d.ts.map +0 -1
  116. package/dist/types/src/context/binder.d.ts +0 -34
  117. package/dist/types/src/context/binder.d.ts.map +0 -1
  118. package/dist/types/src/context/binding.d.ts +0 -56
  119. package/dist/types/src/context/binding.d.ts.map +0 -1
  120. package/dist/types/src/context/index.d.ts +0 -3
  121. package/dist/types/src/context/index.d.ts.map +0 -1
  122. package/dist/types/src/research/exa.d.ts +0 -12
  123. package/dist/types/src/research/exa.d.ts.map +0 -1
  124. package/dist/types/src/research/graph.d.ts +0 -51
  125. package/dist/types/src/research/graph.d.ts.map +0 -1
  126. package/dist/types/src/research/graph.test.d.ts +0 -2
  127. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  128. package/dist/types/src/research/index.d.ts +0 -4
  129. package/dist/types/src/research/index.d.ts.map +0 -1
  130. package/dist/types/src/research/research.d.ts +0 -10
  131. package/dist/types/src/research/research.d.ts.map +0 -1
  132. package/dist/types/src/research/research.test.d.ts +0 -2
  133. package/dist/types/src/research/research.test.d.ts.map +0 -1
  134. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  135. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  136. package/dist/types/src/templates/prompt.d.ts +0 -30
  137. package/dist/types/src/templates/prompt.d.ts.map +0 -1
  138. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  139. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  140. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  141. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  142. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  143. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  144. package/dist/types/src/testing/index.d.ts +0 -3
  145. package/dist/types/src/testing/index.d.ts.map +0 -1
  146. package/src/context/binder.ts +0 -103
  147. package/src/context/binding.ts +0 -32
  148. package/src/context/index.ts +0 -6
  149. package/src/research/exa.ts +0 -97
  150. package/src/research/graph.test.ts +0 -64
  151. package/src/research/graph.ts +0 -369
  152. package/src/research/index.ts +0 -7
  153. package/src/research/instructions-research.tpl +0 -98
  154. package/src/research/research.test.ts +0 -190
  155. package/src/research/research.ts +0 -87
  156. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  157. package/src/session/version-pin.test.ts +0 -7
  158. package/src/templates/assistant.tpl +0 -111
  159. package/src/templates/prompt.ts +0 -45
  160. package/src/testing/exa-search-1748337321991.ts +0 -131
  161. package/src/testing/exa-search-1748337331526.ts +0 -144
  162. package/src/testing/exa-search-1748337344119.ts +0 -133
  163. package/src/testing/index.ts +0 -11
  164. 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.b97322e",
3
+ "version": "0.8.4-main.c4373fc",
4
4
  "description": "Natural language interface to DXOS",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -10,52 +10,64 @@
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
- "@effect/ai": "0.23.0",
25
- "@effect/ai-anthropic": "^0.13.0",
26
- "@effect/platform": "^0.89.0",
27
- "@effect/platform-node": "^0.92.0",
28
- "@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",
29
46
  "@xenova/transformers": "^2.17.2",
30
- "chalk": "^4.1.0",
31
- "exa-js": "^1.5.12",
32
- "handlebars": "4.7.8",
33
47
  "lodash.defaultsdeep": "^4.6.1",
34
- "@dxos/ai": "0.8.4-main.b97322e",
35
- "@dxos/async": "0.8.4-main.b97322e",
36
- "@dxos/context": "0.8.4-main.b97322e",
37
- "@dxos/blueprints": "0.8.4-main.b97322e",
38
- "@dxos/debug": "0.8.4-main.b97322e",
39
- "@dxos/echo": "0.8.4-main.b97322e",
40
- "@dxos/echo-db": "0.8.4-main.b97322e",
41
- "@dxos/effect": "0.8.4-main.b97322e",
42
- "@dxos/echo-schema": "0.8.4-main.b97322e",
43
- "@dxos/errors": "0.8.4-main.b97322e",
44
- "@dxos/functions": "0.8.4-main.b97322e",
45
- "@dxos/invariant": "0.8.4-main.b97322e",
46
- "@dxos/graph": "0.8.4-main.b97322e",
47
- "@dxos/keys": "0.8.4-main.b97322e",
48
- "@dxos/log": "0.8.4-main.b97322e",
49
- "@dxos/live-object": "0.8.4-main.b97322e",
50
- "@dxos/node-std": "0.8.4-main.b97322e",
51
- "@dxos/schema": "0.8.4-main.b97322e",
52
- "@dxos/util": "0.8.4-main.b97322e",
53
- "@dxos/echo-protocol": "0.8.4-main.b97322e"
48
+ "@dxos/async": "0.8.4-main.c4373fc",
49
+ "@dxos/blueprints": "0.8.4-main.c4373fc",
50
+ "@dxos/ai": "0.8.4-main.c4373fc",
51
+ "@dxos/context": "0.8.4-main.c4373fc",
52
+ "@dxos/debug": "0.8.4-main.c4373fc",
53
+ "@dxos/echo": "0.8.4-main.c4373fc",
54
+ "@dxos/echo-db": "0.8.4-main.c4373fc",
55
+ "@dxos/echo-protocol": "0.8.4-main.c4373fc",
56
+ "@dxos/effect": "0.8.4-main.c4373fc",
57
+ "@dxos/graph": "0.8.4-main.c4373fc",
58
+ "@dxos/invariant": "0.8.4-main.c4373fc",
59
+ "@dxos/errors": "0.8.4-main.c4373fc",
60
+ "@dxos/keys": "0.8.4-main.c4373fc",
61
+ "@dxos/live-object": "0.8.4-main.c4373fc",
62
+ "@dxos/log": "0.8.4-main.c4373fc",
63
+ "@dxos/schema": "0.8.4-main.c4373fc",
64
+ "@dxos/util": "0.8.4-main.c4373fc",
65
+ "@dxos/node-std": "0.8.4-main.c4373fc",
66
+ "@dxos/functions": "0.8.4-main.c4373fc"
54
67
  },
55
68
  "devDependencies": {
56
69
  "@types/lodash.defaultsdeep": "^4.6.6",
57
- "effect": "3.17.0",
58
- "inquirer": "^12.0.0"
70
+ "effect": "3.18.3"
59
71
  },
60
72
  "peerDependencies": {
61
73
  "effect": "^3.13.3"
@@ -65,6 +77,6 @@
65
77
  },
66
78
  "beast": {},
67
79
  "scripts": {
68
- "run:chat": "tsx ./bin/chat.ts"
80
+ "run:chat": "vite-node ./bin/chat.ts"
69
81
  }
70
82
  }
@@ -0,0 +1,156 @@
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 { DXN, Obj, type Ref, type Relation, Type } from '@dxos/echo';
13
+ import { type Queue } from '@dxos/echo-db';
14
+ import { ComplexSet } from '@dxos/util';
15
+
16
+ /**
17
+ * Thread message that binds or unbinds contextual objects to a conversation.
18
+ */
19
+ // TODO(burdon): Move to @dxos/schema ContentBlock?
20
+ export const ContextBinding = Schema.Struct({
21
+ blueprints: Schema.Struct({
22
+ added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
23
+ removed: Schema.Array(Type.Ref(Blueprint.Blueprint)),
24
+ }),
25
+
26
+ // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)
27
+ objects: Schema.Struct({
28
+ added: Schema.Array(Type.Ref(Type.Expando)),
29
+ removed: Schema.Array(Type.Ref(Type.Expando)),
30
+ }),
31
+ }).pipe(
32
+ Type.Obj({
33
+ typename: 'dxos.org/type/ContextBinding',
34
+ version: '0.1.0',
35
+ }),
36
+ );
37
+
38
+ export interface ContextBinding extends Schema.Schema.Type<typeof ContextBinding> {}
39
+
40
+ export type BindingProps = Partial<{
41
+ blueprints: Ref.Ref<Blueprint.Blueprint>[];
42
+ objects: Ref.Ref<Type.Expando>[];
43
+ }>;
44
+
45
+ export class Bindings {
46
+ readonly blueprints = new ComplexSet<Ref.Ref<Blueprint.Blueprint>>((ref) => ref.dxn.toString());
47
+ // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
48
+ readonly objects = new ComplexSet<Ref.Ref<Type.Expando>>((ref) => ref.dxn.asEchoDXN()?.echoId);
49
+
50
+ toJSON() {
51
+ return {
52
+ blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
53
+ objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString()),
54
+ };
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Manages bindings of blueprints and objects to a conversation.
60
+ */
61
+ // TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?
62
+ export class AiContextBinder {
63
+ /**
64
+ * Reactive query of all bindings.
65
+ */
66
+ // TODO(burdon): Cache value?
67
+ readonly bindings: ReadonlySignal<Bindings> = computed(() => this._reduce(this._queue.objects));
68
+
69
+ readonly blueprints: ReadonlySignal<Ref.Ref<Blueprint.Blueprint>[]> = computed(() => [
70
+ ...this.bindings.value.blueprints,
71
+ ]);
72
+
73
+ readonly objects: ReadonlySignal<Ref.Ref<Type.Expando>[]> = computed(() => [...this.bindings.value.objects]);
74
+
75
+ constructor(private readonly _queue: Queue) {}
76
+
77
+ /**
78
+ * Asynchronous query of all bindings.
79
+ */
80
+ async query(): Promise<Bindings> {
81
+ const queueItems = await this._queue.queryObjects();
82
+ return this._reduce(queueItems);
83
+ }
84
+
85
+ // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
86
+ async bind(props: BindingProps): Promise<void> {
87
+ if (!props.blueprints?.length && !props.objects?.length) {
88
+ return;
89
+ }
90
+
91
+ const blueprints =
92
+ props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ??
93
+ [];
94
+ const objects =
95
+ props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
96
+
97
+ await this._queue.append([
98
+ Obj.make(ContextBinding, {
99
+ blueprints: {
100
+ added: blueprints,
101
+ removed: [],
102
+ },
103
+ objects: {
104
+ added: objects,
105
+ removed: [],
106
+ },
107
+ }),
108
+ ]);
109
+ }
110
+
111
+ async unbind(props: BindingProps): Promise<void> {
112
+ if (!props.blueprints?.length && !props.objects?.length) {
113
+ return;
114
+ }
115
+
116
+ await this._queue.append([
117
+ Obj.make(ContextBinding, {
118
+ blueprints: {
119
+ added: [],
120
+ removed: props.blueprints ?? [],
121
+ },
122
+ objects: {
123
+ added: [],
124
+ removed: props.objects ?? [],
125
+ },
126
+ }),
127
+ ]);
128
+ }
129
+
130
+ private _reduce(items: (Obj.Any | Relation.Any)[]): Bindings {
131
+ return Function.pipe(
132
+ items,
133
+ Array.filter(Obj.instanceOf(ContextBinding)),
134
+ Array.reduce(new Bindings(), (context, item) => {
135
+ item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
136
+ item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
137
+ item.objects.removed.forEach((ref) => {
138
+ for (const obj of context.objects) {
139
+ if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
140
+ context.objects.delete(obj);
141
+ }
142
+ }
143
+ });
144
+ item.objects.added.forEach((ref) => context.objects.add(ref));
145
+ return context;
146
+ }),
147
+ );
148
+ }
149
+ }
150
+
151
+ export class AiContextService extends Context.Tag('@dxos/assistant/AiContextService')<
152
+ AiContextService,
153
+ {
154
+ binder: AiContextBinder;
155
+ }
156
+ >() {}
@@ -2,95 +2,120 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type AiError, type AiLanguageModel, type AiTool, type AiToolkit } from '@effect/ai';
6
- import { Effect } from 'effect';
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';
7
9
 
8
- import {
9
- type ToolExecutionService,
10
- type ToolResolverService,
11
- type AiInputPreprocessingError,
12
- type AiToolNotFoundError,
13
- } from '@dxos/ai';
14
- import { Event } from '@dxos/async';
15
10
  import { Obj } from '@dxos/echo';
16
11
  import { type Queue } from '@dxos/echo-db';
17
12
  import { DatabaseService } from '@dxos/functions';
13
+ import { log } from '@dxos/log';
18
14
  import { DataType } from '@dxos/schema';
19
15
 
20
- import { ContextBinder, type ContextBinding } from '../context';
21
- import type { AiAssistantError } from '../errors';
22
- import { AiSession } from '../session';
16
+ import {
17
+ AiSession,
18
+ type AiSessionRunError,
19
+ type AiSessionRunRequirements,
20
+ type GenerationObserver,
21
+ createToolkit,
22
+ } from '../session';
23
23
 
24
- export interface ConversationRunOptions<Tools extends AiTool.Any> {
25
- systemPrompt?: string;
26
- prompt: string;
24
+ import { AiContextBinder, AiContextService, type ContextBinding } from './context';
27
25
 
28
- toolkit?: AiToolkit.AiToolkit<Tools>;
26
+ export interface AiConversationRunParams {
27
+ prompt: string;
28
+ system?: string;
29
+ observer?: GenerationObserver;
29
30
  }
30
31
 
31
- export type ConversationOptions = {
32
+ export type AiConversationOptions = {
32
33
  queue: Queue<DataType.Message | ContextBinding>;
33
34
  };
34
35
 
35
36
  /**
36
- * Persistent conversation state.
37
- * Context + history + artifacts.
38
- * Backed by a Queue.
37
+ * Durable conversation state (initiated by users and agents) backed by a Queue.
38
+ * Executes tools based on AI responses and supports cancellation of in-progress requests.
39
39
  */
40
- export class Conversation {
40
+ export class AiConversation {
41
+ /**
42
+ * Message and binding queue.
43
+ */
41
44
  private readonly _queue: Queue<DataType.Message | ContextBinding>;
42
45
 
43
46
  /**
44
- * Fired when the execution loop begins.
45
- * This is called before the first message is sent.
47
+ * Blueprints bound to the conversation.
46
48
  */
47
- public readonly onBegin = new Event<AiSession>();
49
+ private readonly _context: AiContextBinder;
48
50
 
49
51
  /**
50
- * Blueprints bound to the conversation.
52
+ * Toolkit from the current session request.
51
53
  */
52
- public readonly context: ContextBinder;
54
+ private _toolkit: Toolkit.WithHandler<any> | undefined;
53
55
 
54
- constructor(options: ConversationOptions) {
56
+ public constructor(options: AiConversationOptions) {
55
57
  this._queue = options.queue;
56
- this.context = new ContextBinder(this._queue);
58
+ this._context = new AiContextBinder(this._queue);
59
+ }
60
+
61
+ public get context() {
62
+ return this._context;
57
63
  }
58
64
 
59
- async getHistory(): Promise<DataType.Message[]> {
65
+ public get toolkit() {
66
+ return this._toolkit;
67
+ }
68
+
69
+ public async getHistory(): Promise<DataType.Message[]> {
60
70
  const queueItems = await this._queue.queryObjects();
61
71
  return queueItems.filter(Obj.instanceOf(DataType.Message));
62
72
  }
63
73
 
64
- run = <Tools extends AiTool.Any>(
65
- options: ConversationRunOptions<Tools>,
66
- ): Effect.Effect<
67
- DataType.Message[],
68
- AiAssistantError | AiInputPreprocessingError | AiError.AiError | AiToolNotFoundError,
69
- AiLanguageModel.AiLanguageModel | ToolResolverService | ToolExecutionService | AiTool.ToHandler<Tools>
70
- > =>
71
- Effect.gen(this, function* () {
74
+ /**
75
+ * Creates a new cancelable request effect.
76
+ */
77
+ createRequest(
78
+ params: AiConversationRunParams,
79
+ ): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> {
80
+ return Effect.gen(this, function* () {
72
81
  const session = new AiSession();
73
- this.onBegin.emit(session);
74
-
75
82
  const history = yield* Effect.promise(() => this.getHistory());
83
+
84
+ // Get context objects.
76
85
  const context = yield* Effect.promise(() => this.context.query());
77
- const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadRef);
86
+ const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(
87
+ Effect.map(Array.filter(Option.isSome)),
88
+ Effect.map(Array.map((option) => option.value)),
89
+ );
90
+ const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(
91
+ Effect.map(Array.filter(Option.isSome)),
92
+ Effect.map(Array.map((option) => option.value)),
93
+ );
94
+
95
+ // Create toolkit.
96
+ const toolkit = yield* createToolkit({ blueprints });
97
+ this._toolkit = toolkit;
98
+
99
+ const start = Date.now();
100
+ log('run', {
101
+ history: history.length,
102
+ blueprints: blueprints.length,
103
+ objects: objects.length,
104
+ tools: this._toolkit?.tools.length ?? 0,
105
+ });
78
106
 
79
- const contextObjects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadRef);
107
+ // Process request.
108
+ const messages = yield* session.run({ history, blueprints, objects, toolkit, ...params }).pipe(
109
+ Effect.provideService(AiContextService, {
110
+ binder: this.context,
111
+ }),
112
+ );
80
113
 
81
- const systemPrompt =
82
- (options.systemPrompt ?? '') +
83
- '\n\n' +
84
- contextObjects.map((obj) => `<object>${Obj.getDXN(obj)}</object>`).join('\n');
114
+ log('result', { messages: messages.length, duration: Date.now() - start });
85
115
 
86
- const messages = yield* session.run({
87
- prompt: options.prompt,
88
- history,
89
- systemPrompt,
90
- toolkit: options.toolkit,
91
- blueprints,
92
- });
116
+ // Append to queue.
93
117
  yield* Effect.promise(() => this._queue.append(messages));
94
118
  return messages;
95
- }).pipe(Effect.withSpan('Conversation.run'));
119
+ }).pipe(Effect.withSpan('AiConversation.request'));
120
+ }
96
121
  }
@@ -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 CHANGED
@@ -4,7 +4,12 @@
4
4
 
5
5
  import { BaseError } from '@dxos/errors';
6
6
 
7
+ /**
8
+ * Generic error from AI model.
9
+ */
10
+ export class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}
11
+
7
12
  /**
8
13
  * Generic error for AI agent execution.
9
14
  */
10
- export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR') {}
15
+ export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}