@dxos/assistant 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (147) hide show
  1. package/README.md +1 -0
  2. package/dist/lib/neutral/extraction/index.mjs +202 -0
  3. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  4. package/dist/lib/neutral/index.mjs +1731 -0
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/types/src/conversation/context.d.ts +120 -64
  8. package/dist/types/src/conversation/context.d.ts.map +1 -1
  9. package/dist/types/src/conversation/context.test.d.ts +2 -0
  10. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  11. package/dist/types/src/conversation/index.d.ts +1 -1
  12. package/dist/types/src/conversation/index.d.ts.map +1 -1
  13. package/dist/types/src/conversation/session.d.ts +78 -0
  14. package/dist/types/src/conversation/session.d.ts.map +1 -0
  15. package/dist/types/src/diff.d.ts +3 -1
  16. package/dist/types/src/diff.d.ts.map +1 -1
  17. package/dist/types/src/errors.d.ts +32 -40
  18. package/dist/types/src/errors.d.ts.map +1 -1
  19. package/dist/types/src/execution-graph.d.ts +5 -2
  20. package/dist/types/src/execution-graph.d.ts.map +1 -1
  21. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  22. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  23. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  24. package/dist/types/src/extraction/extraction.d.ts +1066 -307
  25. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  26. package/dist/types/src/extraction/index.d.ts +0 -1
  27. package/dist/types/src/extraction/index.d.ts.map +1 -1
  28. package/dist/types/src/extraction/quotes.d.ts +3 -3
  29. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  30. package/dist/types/src/functions/services.d.ts +15 -16
  31. package/dist/types/src/functions/services.d.ts.map +1 -1
  32. package/dist/types/src/index.d.ts +1 -0
  33. package/dist/types/src/index.d.ts.map +1 -1
  34. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  35. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  36. package/dist/types/src/session/error-handling.d.ts +2 -2
  37. package/dist/types/src/session/error-handling.d.ts.map +1 -1
  38. package/dist/types/src/session/format.d.ts +8 -177
  39. package/dist/types/src/session/format.d.ts.map +1 -1
  40. package/dist/types/src/session/index.d.ts +2 -1
  41. package/dist/types/src/session/index.d.ts.map +1 -1
  42. package/dist/types/src/session/observer.d.ts +7 -6
  43. package/dist/types/src/session/observer.d.ts.map +1 -1
  44. package/dist/types/src/session/request.d.ts +104 -0
  45. package/dist/types/src/session/request.d.ts.map +1 -0
  46. package/dist/types/src/session/toolkit.d.ts +11 -9
  47. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  48. package/dist/types/src/session/version-pin.d.ts +4 -4
  49. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  50. package/dist/types/src/templates/system.d.ts +1 -2
  51. package/dist/types/src/templates/system.d.ts.map +1 -1
  52. package/dist/types/src/tracing.d.ts +233 -0
  53. package/dist/types/src/tracing.d.ts.map +1 -0
  54. package/dist/types/src/types/artifact.d.ts +28 -0
  55. package/dist/types/src/types/artifact.d.ts.map +1 -0
  56. package/dist/types/src/types/index.d.ts +2 -0
  57. package/dist/types/src/types/index.d.ts.map +1 -0
  58. package/dist/types/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +35 -47
  60. package/src/conversation/context.test.ts +52 -0
  61. package/src/conversation/context.ts +324 -75
  62. package/src/conversation/index.ts +1 -1
  63. package/src/conversation/session.ts +334 -0
  64. package/src/diff.test.ts +37 -6
  65. package/src/diff.ts +18 -4
  66. package/src/errors.ts +2 -2
  67. package/src/execution-graph.test.ts +47 -45
  68. package/src/execution-graph.ts +41 -22
  69. package/src/extraction/extraction-ner-function/index.ts +0 -1
  70. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +10 -5
  71. package/src/extraction/extraction.ts +44 -15
  72. package/src/extraction/index.ts +0 -1
  73. package/src/extraction/quotes.ts +5 -6
  74. package/src/functions/services.ts +126 -65
  75. package/src/functions.conversations.json +1 -0
  76. package/src/index.ts +1 -0
  77. package/src/session/artifact-diff.ts +2 -2
  78. package/src/session/error-handling.ts +4 -3
  79. package/src/session/format.ts +34 -26
  80. package/src/session/index.ts +2 -1
  81. package/src/session/observer.ts +8 -4
  82. package/src/session/request.conversations.json +1 -0
  83. package/src/session/request.ts +342 -0
  84. package/src/session/toolkit.ts +29 -28
  85. package/src/session/version-pin.ts +7 -7
  86. package/src/templates/{format.tpl → instructions/format.tpl} +1 -4
  87. package/src/templates/{system.tpl → instructions/system.tpl} +50 -2
  88. package/src/templates/system.ts +9 -8
  89. package/src/tracing.ts +57 -0
  90. package/src/{types.ts → types/artifact.ts} +44 -7
  91. package/src/types/index.ts +5 -0
  92. package/dist/lib/browser/chunk-ILL2CN3G.mjs +0 -374
  93. package/dist/lib/browser/chunk-ILL2CN3G.mjs.map +0 -7
  94. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  95. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  96. package/dist/lib/browser/extraction/index.mjs +0 -272
  97. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  98. package/dist/lib/browser/index.mjs +0 -861
  99. package/dist/lib/browser/index.mjs.map +0 -7
  100. package/dist/lib/browser/meta.json +0 -1
  101. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  102. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map +0 -7
  103. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  104. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  105. package/dist/lib/node-esm/chunk-GVKA7VL3.mjs +0 -376
  106. package/dist/lib/node-esm/chunk-GVKA7VL3.mjs.map +0 -7
  107. package/dist/lib/node-esm/extraction/index.mjs +0 -273
  108. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  109. package/dist/lib/node-esm/index.mjs +0 -862
  110. package/dist/lib/node-esm/index.mjs.map +0 -7
  111. package/dist/lib/node-esm/meta.json +0 -1
  112. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  113. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +0 -7
  114. package/dist/types/src/conversation/conversation.d.ts +0 -41
  115. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  116. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  117. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  118. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  119. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  120. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  121. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  122. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -341
  123. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  124. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  125. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  126. package/dist/types/src/session/format.test.d.ts +0 -2
  127. package/dist/types/src/session/format.test.d.ts.map +0 -1
  128. package/dist/types/src/session/session.d.ts +0 -47
  129. package/dist/types/src/session/session.d.ts.map +0 -1
  130. package/dist/types/src/session/session.test.d.ts +0 -2
  131. package/dist/types/src/session/session.test.d.ts.map +0 -1
  132. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  133. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  134. package/dist/types/src/types.d.ts +0 -16
  135. package/dist/types/src/types.d.ts.map +0 -1
  136. package/src/conversation/conversation.ts +0 -119
  137. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  138. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -72
  139. package/src/extraction/extraction-llm-function/index.ts +0 -5
  140. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  141. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -64
  142. package/src/session/format.test.ts +0 -60
  143. package/src/session/session.conversations.json +0 -1
  144. package/src/session/session.test.ts +0 -146
  145. package/src/session/session.ts +0 -206
  146. package/src/summarization/summarization.test.ts +0 -201
  147. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "@dxos/assistant",
3
- "version": "0.8.4-main.a4bbb77",
3
+ "version": "0.8.4-main.abd8ff62ef",
4
4
  "description": "Natural language interface to DXOS",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
7
11
  "license": "MIT",
8
12
  "author": "info@dxos.org",
9
13
  "sideEffects": true,
@@ -12,71 +16,55 @@
12
16
  ".": {
13
17
  "source": "./src/index.ts",
14
18
  "types": "./dist/types/src/index.d.ts",
15
- "browser": "./dist/lib/browser/index.mjs",
16
- "node": "./dist/lib/node-esm/index.mjs"
19
+ "default": "./dist/lib/neutral/index.mjs"
17
20
  },
18
21
  "./extraction": {
19
22
  "source": "./src/extraction/index.ts",
20
23
  "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"
24
+ "default": "./dist/lib/neutral/extraction/index.mjs"
23
25
  }
24
26
  },
25
27
  "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
- },
36
28
  "files": [
37
29
  "dist",
38
30
  "src"
39
31
  ],
40
32
  "dependencies": {
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",
33
+ "@automerge/automerge": "3.2.3",
34
+ "@effect-atom/atom": "^0.5.1",
35
+ "@effect-atom/atom-react": "^0.5.0",
36
+ "@effect/ai": "0.33.2",
37
+ "@effect/experimental": "0.58.0",
38
+ "@effect/platform": "0.94.4",
48
39
  "@xenova/transformers": "^2.17.2",
49
- "chalk": "^4.1.0",
50
- "handlebars": "4.7.8",
51
40
  "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"
41
+ "@dxos/ai": "0.8.4-main.abd8ff62ef",
42
+ "@dxos/context": "0.8.4-main.abd8ff62ef",
43
+ "@dxos/compute": "0.8.4-main.abd8ff62ef",
44
+ "@dxos/async": "0.8.4-main.abd8ff62ef",
45
+ "@dxos/echo-db": "0.8.4-main.abd8ff62ef",
46
+ "@dxos/debug": "0.8.4-main.abd8ff62ef",
47
+ "@dxos/echo": "0.8.4-main.abd8ff62ef",
48
+ "@dxos/echo-protocol": "0.8.4-main.abd8ff62ef",
49
+ "@dxos/errors": "0.8.4-main.abd8ff62ef",
50
+ "@dxos/effect": "0.8.4-main.abd8ff62ef",
51
+ "@dxos/functions": "0.8.4-main.abd8ff62ef",
52
+ "@dxos/invariant": "0.8.4-main.abd8ff62ef",
53
+ "@dxos/mcp-client": "0.8.4-main.abd8ff62ef",
54
+ "@dxos/keys": "0.8.4-main.abd8ff62ef",
55
+ "@dxos/log": "0.8.4-main.abd8ff62ef",
56
+ "@dxos/node-std": "0.8.4-main.abd8ff62ef",
57
+ "@dxos/schema": "0.8.4-main.abd8ff62ef",
58
+ "@dxos/util": "0.8.4-main.abd8ff62ef",
59
+ "@dxos/graph": "0.8.4-main.abd8ff62ef",
60
+ "@dxos/types": "0.8.4-main.abd8ff62ef"
72
61
  },
73
62
  "devDependencies": {
74
63
  "@types/lodash.defaultsdeep": "^4.6.6",
75
- "effect": "3.18.3",
76
- "inquirer": "^12.0.0"
64
+ "effect": "3.20.0"
77
65
  },
78
66
  "peerDependencies": {
79
- "effect": "^3.13.3"
67
+ "effect": "3.20.0"
80
68
  },
81
69
  "publishConfig": {
82
70
  "access": "public"
@@ -0,0 +1,52 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
8
+ import * as Runtime from 'effect/Runtime';
9
+ import * as Schema from 'effect/Schema';
10
+ import { describe, it } from 'vitest';
11
+
12
+ import { Feed, Obj, Ref, Type } from '@dxos/echo';
13
+
14
+ import { AiContextBinder } from './context';
15
+
16
+ const createMockFeedRuntime = (): Runtime.Runtime<Feed.FeedService> => {
17
+ const mockFeedService: Context.Tag.Service<Feed.FeedService> = {
18
+ append: async () => {},
19
+ remove: async () => {},
20
+ query: () =>
21
+ ({
22
+ subscribe: () => () => {},
23
+ results: [],
24
+ run: async () => [],
25
+ }) as any,
26
+ };
27
+ const layer = Layer.succeed(Feed.FeedService, mockFeedService);
28
+ return Effect.runSync(Effect.runtime<Feed.FeedService>().pipe(Effect.provide(layer)));
29
+ };
30
+
31
+ describe('AiContextBinder', () => {
32
+ it('should handle bind with Ref', async () => {
33
+ const feed = Feed.make();
34
+ const runtime = createMockFeedRuntime();
35
+ const binder = new AiContextBinder({ feed, runtime });
36
+
37
+ const TestSchema = Schema.Struct({}).pipe(
38
+ Type.object({
39
+ typename: 'org.dxos.type.example',
40
+ version: '0.1.0',
41
+ }),
42
+ );
43
+
44
+ const obj = Obj.make(TestSchema, {});
45
+ const ref = Ref.make(obj);
46
+
47
+ await binder.bind({
48
+ blueprints: [],
49
+ objects: [ref],
50
+ });
51
+ });
52
+ });
@@ -2,14 +2,20 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type ReadonlySignal, computed } from '@preact/signals-core';
6
- import { Context, Schema } from 'effect';
7
- import { Array, pipe } from 'effect';
5
+ import { Atom, Registry } from '@effect-atom/atom-react';
6
+ import * as EArray from 'effect/Array';
7
+ import * as Context from 'effect/Context';
8
+ import * as Effect from 'effect/Effect';
9
+ import * as Function from 'effect/Function';
10
+ import * as Runtime from 'effect/Runtime';
11
+ import * as Schema from 'effect/Schema';
8
12
 
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
+ import { Blueprint } from '@dxos/compute';
14
+ import { Resource } from '@dxos/context';
15
+ import { DXN, Feed, Obj, type QueryResult, Query, Ref, Type } from '@dxos/echo';
16
+ import { assertArgument } from '@dxos/invariant';
17
+ import { log } from '@dxos/log';
18
+ import { ComplexSet, isNonNullable } from '@dxos/util';
13
19
 
14
20
  /**
15
21
  * Thread message that binds or unbinds contextual objects to a conversation.
@@ -17,18 +23,17 @@ import { ComplexSet } from '@dxos/util';
17
23
  // TODO(burdon): Move to @dxos/schema ContentBlock?
18
24
  export const ContextBinding = Schema.Struct({
19
25
  blueprints: Schema.Struct({
20
- added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
21
- removed: Schema.Array(Type.Ref(Blueprint.Blueprint)),
26
+ added: Schema.Array(Ref.Ref(Blueprint.Blueprint)),
27
+ removed: Schema.Array(Ref.Ref(Blueprint.Blueprint)),
22
28
  }),
23
29
 
24
- // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)
25
30
  objects: Schema.Struct({
26
- added: Schema.Array(Type.Ref(Type.Expando)),
27
- removed: Schema.Array(Type.Ref(Type.Expando)),
31
+ added: Schema.Array(Ref.Ref(Obj.Unknown)),
32
+ removed: Schema.Array(Ref.Ref(Obj.Unknown)),
28
33
  }),
29
34
  }).pipe(
30
- Type.Obj({
31
- typename: 'dxos.org/type/ContextBinding',
35
+ Type.object({
36
+ typename: 'org.dxos.type.contextBinding',
32
37
  version: '0.1.0',
33
38
  }),
34
39
  );
@@ -37,113 +42,342 @@ export interface ContextBinding extends Schema.Schema.Type<typeof ContextBinding
37
42
 
38
43
  export type BindingProps = Partial<{
39
44
  blueprints: Ref.Ref<Blueprint.Blueprint>[];
40
- objects: Ref.Ref<Type.Expando>[];
45
+ objects: Ref.Ref<Obj.Unknown>[];
41
46
  }>;
42
47
 
43
48
  export class Bindings {
44
49
  readonly blueprints = new ComplexSet<Ref.Ref<Blueprint.Blueprint>>((ref) => ref.dxn.toString());
50
+
45
51
  // 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);
52
+ readonly objects = new ComplexSet<Ref.Ref<Obj.Unknown>>((ref) => ref.dxn.asEchoDXN()?.echoId);
47
53
 
48
54
  toJSON() {
49
55
  return {
50
- blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
51
- objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString()),
56
+ blueprints: EArray.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
57
+ objects: EArray.fromIterable(this.objects).map((ref) => ref.dxn.toString()),
52
58
  };
53
59
  }
54
60
  }
55
61
 
62
+ export type AiContextBinderOptions = {
63
+ feed: Feed.Feed;
64
+ runtime: Runtime.Runtime<Feed.FeedService>;
65
+ registry?: Registry.Registry;
66
+ };
67
+
56
68
  /**
57
69
  * Manages bindings of blueprints and objects to a conversation.
58
70
  */
59
71
  // TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?
60
- export class AiContextBinder {
72
+ export class AiContextBinder extends Resource {
73
+ private readonly _blueprints = Atom.make<Blueprint.Blueprint[]>([]).pipe(Atom.keepAlive);
74
+ private readonly _objects = Atom.make<Obj.Unknown[]>([]).pipe(Atom.keepAlive);
75
+ private readonly _registry: Registry.Registry;
76
+ private readonly _feed: Feed.Feed;
77
+ private readonly _runtime: Runtime.Runtime<Feed.FeedService>;
78
+ #bindingsQuery: QueryResult.QueryResult<ContextBinding> | undefined;
79
+
80
+ constructor(options: AiContextBinderOptions) {
81
+ super();
82
+ assertArgument(options.feed, 'options.feed', 'Feed is required');
83
+ assertArgument(options.runtime, 'options.runtime', 'Feed runtime is required');
84
+ this._feed = options.feed;
85
+ this._runtime = options.runtime;
86
+ this._registry = options.registry ?? Registry.make();
87
+ }
88
+
61
89
  /**
62
- * Reactive query of all bindings.
90
+ * Returns the blueprints atom for subscription.
63
91
  */
64
- // TODO(burdon): Cache value?
65
- readonly bindings: ReadonlySignal<Bindings> = computed(() => this._reduce(this._queue.objects));
92
+ get blueprints(): Atom.Atom<Blueprint.Blueprint[]> {
93
+ return this._blueprints;
94
+ }
66
95
 
67
- readonly blueprints: ReadonlySignal<Ref.Ref<Blueprint.Blueprint>[]> = computed(() => [
68
- ...this.bindings.value.blueprints,
69
- ]);
96
+ /**
97
+ * Returns the objects atom for subscription.
98
+ */
99
+ get objects(): Atom.Atom<Obj.Unknown[]> {
100
+ return this._objects;
101
+ }
70
102
 
71
- readonly objects: ReadonlySignal<Ref.Ref<Type.Expando>[]> = computed(() => [...this.bindings.value.objects]);
103
+ /**
104
+ * Gets the current blueprints value.
105
+ */
106
+ getBlueprints(): Blueprint.Blueprint[] {
107
+ return this._registry.get(this._blueprints);
108
+ }
109
+
110
+ /**
111
+ * Gets the current objects value.
112
+ */
113
+ getObjects(): Obj.Unknown[] {
114
+ return this._registry.get(this._objects);
115
+ }
72
116
 
73
- constructor(private readonly _queue: Queue) {}
117
+ /**
118
+ * Subscribe to changes in blueprints.
119
+ */
120
+ subscribeBlueprints(cb: (blueprints: Blueprint.Blueprint[]) => void): () => void {
121
+ return this._registry.subscribe(this._blueprints, () => cb(this._registry.get(this._blueprints)));
122
+ }
74
123
 
75
124
  /**
76
- * Asynchronous query of all bindings.
125
+ * Subscribe to changes in objects.
77
126
  */
78
- async query(): Promise<Bindings> {
79
- const queueItems = await this._queue.queryObjects();
80
- return this._reduce(queueItems);
127
+ subscribeObjects(cb: (objects: Obj.Unknown[]) => void): () => void {
128
+ return this._registry.subscribe(this._objects, () => cb(this._registry.get(this._objects)));
81
129
  }
82
130
 
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) {
131
+ protected override async _open(): Promise<void> {
132
+ this.#bindingsQuery = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Query.type(ContextBinding)));
133
+
134
+ // Process initial state before returning.
135
+ const initialResults = await this.#bindingsQuery.run();
136
+ await this._updateBindings(initialResults);
137
+
138
+ // Subscribe to future changes.
139
+ this._ctx.onDispose(
140
+ this.#bindingsQuery.subscribe(async () => {
141
+ await this._updateBindings(this.#bindingsQuery!.results);
142
+ }),
143
+ );
144
+ }
145
+
146
+ /**
147
+ * Re-reads bindings from the feed to pick up changes made by other processes.
148
+ */
149
+ async sync(): Promise<void> {
150
+ if (this.#bindingsQuery) {
151
+ const results = await this.#bindingsQuery.run();
152
+ log('sync', { bindingItems: results.length });
153
+ await this._updateBindings(results);
154
+ log('sync complete', {
155
+ blueprints: this._registry.get(this._blueprints).length,
156
+ blueprintKeys: this._registry.get(this._blueprints).map((bp) => (bp as any).key),
157
+ });
158
+ }
159
+ }
160
+
161
+ private async _updateBindings(items: ContextBinding[]): Promise<void> {
162
+ // Skip update if no items - preserve existing state set by bind().
163
+ if (items.length === 0) {
86
164
  return;
87
165
  }
88
166
 
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
- ]);
167
+ const bindings = this._reduce(items);
168
+
169
+ log('_updateBindings', {
170
+ items: items.length,
171
+ blueprintRefs: [...bindings.blueprints].map((ref) => ({ dxn: ref.dxn.toString(), available: ref.isAvailable })),
172
+ });
173
+
174
+ // Resolve references (loading them first if needed).
175
+ const currentBlueprints = this._registry.get(this._blueprints);
176
+ const currentObjects = this._registry.get(this._objects);
177
+ const resolvedBlueprints = await this._resolve(bindings.blueprints, currentBlueprints);
178
+ const resolvedObjects = await this._resolve(bindings.objects, currentObjects);
179
+
180
+ log('_updateBindings resolved', {
181
+ resolvedBlueprints: resolvedBlueprints.length,
182
+ resolvedBlueprintKeys: resolvedBlueprints.map((bp) => (bp as any).key),
183
+ });
184
+
185
+ // Filter current state to only items still in the reduced binding set,
186
+ // then merge in newly resolved items. This ensures unbind events are respected.
187
+ const reducedBlueprintDxns = new ComplexSet<DXN>(
188
+ DXN.hash,
189
+ [...bindings.blueprints].map((ref) => ref.dxn),
190
+ );
191
+ const reducedObjectDxns = new ComplexSet<DXN>(
192
+ DXN.hash,
193
+ [...bindings.objects].map((ref) => ref.dxn),
194
+ );
195
+ const filteredBlueprints = currentBlueprints.filter((obj) => reducedBlueprintDxns.has(Obj.getDXN(obj)));
196
+ const filteredObjects = currentObjects.filter((obj) => reducedObjectDxns.has(Obj.getDXN(obj)));
197
+ const mergedBlueprints = this._mergeInto(filteredBlueprints, resolvedBlueprints);
198
+ const mergedObjects = this._mergeInto(filteredObjects, resolvedObjects);
199
+
200
+ this._registry.set(this._blueprints, mergedBlueprints);
201
+ this._registry.set(this._objects, mergedObjects);
202
+
203
+ log('updated bindings', {
204
+ blueprints: mergedBlueprints.length,
205
+ objects: mergedObjects.length,
206
+ });
207
+ }
208
+
209
+ protected override async _close(): Promise<void> {
210
+ // Reset atoms to empty state.
211
+ this._registry.set(this._blueprints, []);
212
+ this._registry.set(this._objects, []);
107
213
  }
108
214
 
109
- async unbind(props: BindingProps): Promise<void> {
110
- if (!props.blueprints?.length && !props.objects?.length) {
215
+ async bind({ blueprints, objects }: BindingProps): Promise<void> {
216
+ const currentBlueprints = this._registry.get(this._blueprints);
217
+ const currentObjects = this._registry.get(this._objects);
218
+
219
+ const { added: addedBlueprints, next: nextBlueprints } = this._processBindings(blueprints, currentBlueprints);
220
+ const { added: addedObjects, next: nextObjects } = this._processBindings(objects, currentObjects);
221
+ if (!addedBlueprints.length && !addedObjects.length) {
111
222
  return;
112
223
  }
113
224
 
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
- ]);
225
+ // Atomic updates - subscribers notified automatically.
226
+ this._registry.set(this._blueprints, nextBlueprints);
227
+ this._registry.set(this._objects, nextObjects);
228
+
229
+ log('bind', { blueprints: addedBlueprints.length, objects: addedObjects.length });
230
+ await Runtime.runPromise(this._runtime)(
231
+ Feed.append(this._feed, [
232
+ Obj.make(ContextBinding, {
233
+ blueprints: {
234
+ added: addedBlueprints,
235
+ removed: [],
236
+ },
237
+ objects: {
238
+ added: addedObjects,
239
+ removed: [],
240
+ },
241
+ }),
242
+ ]),
243
+ );
126
244
  }
127
245
 
128
- private _reduce(items: (Obj.Any | Relation.Any)[]): Bindings {
129
- return pipe(
246
+ async unbind({ blueprints, objects }: BindingProps): Promise<void> {
247
+ if (!blueprints?.length && !objects?.length) {
248
+ return;
249
+ }
250
+
251
+ // Immediately update atom state so removals are reflected before the queue round-trips.
252
+ const removedBlueprintDxns = (blueprints ?? []).map((ref) => ref.dxn);
253
+ const removedObjectDxns = (objects ?? []).map((ref) => ref.dxn);
254
+ if (removedBlueprintDxns.length > 0) {
255
+ const current = this._registry.get(this._blueprints);
256
+ this._registry.set(
257
+ this._blueprints,
258
+ current.filter((obj) => !removedBlueprintDxns.some((dxn) => DXN.equalsEchoId(Obj.getDXN(obj), dxn))),
259
+ );
260
+ }
261
+ if (removedObjectDxns.length > 0) {
262
+ const current = this._registry.get(this._objects);
263
+ this._registry.set(
264
+ this._objects,
265
+ current.filter((obj) => !removedObjectDxns.some((dxn) => DXN.equalsEchoId(Obj.getDXN(obj), dxn))),
266
+ );
267
+ }
268
+
269
+ log('unbind', { blueprints: blueprints?.length, objects: objects?.length });
270
+ await Runtime.runPromise(this._runtime)(
271
+ Feed.append(this._feed, [
272
+ Obj.make(ContextBinding, {
273
+ blueprints: {
274
+ added: [],
275
+ removed: blueprints ?? [],
276
+ },
277
+ objects: {
278
+ added: [],
279
+ removed: objects ?? [],
280
+ },
281
+ }),
282
+ ]),
283
+ );
284
+ }
285
+
286
+ /**
287
+ * Process bindings to filter duplicates and determine next state.
288
+ */
289
+ private _processBindings<T extends Obj.Unknown>(
290
+ refs: Ref.Ref<T>[] | undefined,
291
+ current: T[],
292
+ ): { added: Ref.Ref<T>[]; next: T[] } {
293
+ const next = [...current];
294
+ const added: Ref.Ref<T>[] = [];
295
+ if (!refs?.length) {
296
+ return { added, next };
297
+ }
298
+
299
+ const seen = new Set(current.map((obj) => Obj.getDXN(obj).toString()));
300
+ for (const ref of refs) {
301
+ const dxn = ref.dxn.toString();
302
+ if (!seen.has(dxn)) {
303
+ seen.add(dxn);
304
+ added.push(ref);
305
+
306
+ // Only resolve target if available (has target or resolver).
307
+ if (ref.isAvailable) {
308
+ const target = ref.target;
309
+ if (target) {
310
+ next.push(target);
311
+ }
312
+ }
313
+ }
314
+ }
315
+
316
+ return { added, next };
317
+ }
318
+
319
+ /**
320
+ * Reduce results into sets of blueprints and objects.
321
+ */
322
+ private _reduce(items: ContextBinding[]): Bindings {
323
+ return Function.pipe(
130
324
  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) => {
325
+ EArray.reduce(new Bindings(), (context, { blueprints, objects }) => {
326
+ blueprints.added.forEach((ref) => context.blueprints.add(ref));
327
+ blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
328
+
329
+ objects.added.forEach((ref) => context.objects.add(ref));
330
+ objects.removed.forEach((ref) => {
136
331
  for (const obj of context.objects) {
137
332
  if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
138
333
  context.objects.delete(obj);
139
334
  }
140
335
  }
141
336
  });
142
- item.objects.added.forEach((ref) => context.objects.add(ref));
337
+
143
338
  return context;
144
339
  }),
145
340
  );
146
341
  }
342
+
343
+ /**
344
+ * Merge resolved items into the current set, adding only items not already present (by DXN).
345
+ */
346
+ private _mergeInto<T extends Obj.Unknown>(current: T[], resolved: T[]): T[] {
347
+ const seen = new Set(current.map((obj) => Obj.getDXN(obj).toString()));
348
+ const merged = [...current];
349
+ for (const obj of resolved) {
350
+ const dxn = Obj.getDXN(obj).toString();
351
+ if (!seen.has(dxn)) {
352
+ seen.add(dxn);
353
+ merged.push(obj);
354
+ }
355
+ }
356
+ return merged;
357
+ }
358
+
359
+ /**
360
+ * Resolve references to objects, loading them first if needed and falling back to existing objects.
361
+ */
362
+ private async _resolve<T extends Obj.Unknown>(refs: Iterable<Ref.Ref<T>>, current: T[]): Promise<T[]> {
363
+ const refArray = [...refs];
364
+
365
+ // Load all refs that need loading.
366
+ await Promise.all(refArray.map((ref) => ref.tryLoad()));
367
+
368
+ return refArray
369
+ .map((ref) => {
370
+ let target: T | undefined;
371
+ // Only resolve target if available (has target or resolver).
372
+ if (ref.isAvailable) {
373
+ target = ref.target;
374
+ }
375
+
376
+ // Fallback to existing object.
377
+ return target ?? current.find((obj) => Obj.getDXN(obj as any).toString() === ref.dxn.toString());
378
+ })
379
+ .filter(isNonNullable);
380
+ }
147
381
  }
148
382
 
149
383
  export class AiContextService extends Context.Tag('@dxos/assistant/AiContextService')<
@@ -151,4 +385,19 @@ export class AiContextService extends Context.Tag('@dxos/assistant/AiContextServ
151
385
  {
152
386
  binder: AiContextBinder;
153
387
  }
154
- >() {}
388
+ >() {
389
+ static bindContext = ({ blueprints, objects }: BindingProps): Effect.Effect<void, never, AiContextService> =>
390
+ Effect.gen(function* () {
391
+ const { binder } = yield* AiContextService;
392
+ yield* Effect.promise(() => binder.bind({ blueprints, objects }));
393
+ });
394
+
395
+ static findObjects = <T extends Type.AnyEntity>(
396
+ type: T,
397
+ ): Effect.Effect<Schema.Schema.Type<T>[], never, AiContextService> => {
398
+ return Effect.gen(function* () {
399
+ const { binder } = yield* AiContextService;
400
+ return binder.getObjects().filter(Obj.instanceOf(type));
401
+ });
402
+ };
403
+ }
@@ -3,4 +3,4 @@
3
3
  //
4
4
 
5
5
  export * from './context';
6
- export * from './conversation';
6
+ export * from './session';