@dxos/assistant 0.8.4-main.ead640a → 0.8.4-main.ef1bc66f44

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 (120) hide show
  1. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/neutral/chunk-ZPC54VRM.mjs +596 -0
  3. package/dist/lib/neutral/chunk-ZPC54VRM.mjs.map +7 -0
  4. package/dist/lib/neutral/extraction/index.mjs +225 -0
  5. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  6. package/dist/lib/{browser → neutral}/index.mjs +346 -350
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/neutral/testing/index.mjs +38 -0
  10. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  11. package/dist/types/src/conversation/context.d.ts +97 -62
  12. package/dist/types/src/conversation/context.d.ts.map +1 -1
  13. package/dist/types/src/conversation/context.test.d.ts +2 -0
  14. package/dist/types/src/conversation/context.test.d.ts.map +1 -0
  15. package/dist/types/src/conversation/conversation.d.ts +41 -16
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/conversation/conversation.test.d.ts +2 -0
  18. package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
  19. package/dist/types/src/diff.d.ts +3 -1
  20. package/dist/types/src/diff.d.ts.map +1 -1
  21. package/dist/types/src/errors.d.ts +22 -30
  22. package/dist/types/src/errors.d.ts.map +1 -1
  23. package/dist/types/src/execution-graph.d.ts +5 -2
  24. package/dist/types/src/execution-graph.d.ts.map +1 -1
  25. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +254 -248
  27. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  28. package/dist/types/src/extraction/extraction.d.ts +344 -303
  29. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  30. package/dist/types/src/extraction/quotes.d.ts +2 -2
  31. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  32. package/dist/types/src/functions/services.d.ts +6 -6
  33. package/dist/types/src/functions/services.d.ts.map +1 -1
  34. package/dist/types/src/functions.test.d.ts +2 -0
  35. package/dist/types/src/functions.test.d.ts.map +1 -0
  36. package/dist/types/src/session/GenericToolkit.d.ts +107 -0
  37. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  38. package/dist/types/src/session/artifact-diff.d.ts +1 -1
  39. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  40. package/dist/types/src/session/format.d.ts +4 -176
  41. package/dist/types/src/session/format.d.ts.map +1 -1
  42. package/dist/types/src/session/index.d.ts +2 -0
  43. package/dist/types/src/session/index.d.ts.map +1 -1
  44. package/dist/types/src/session/observer.d.ts +6 -5
  45. package/dist/types/src/session/observer.d.ts.map +1 -1
  46. package/dist/types/src/session/session.d.ts +16 -11
  47. package/dist/types/src/session/session.d.ts.map +1 -1
  48. package/dist/types/src/session/toolkit.d.ts +5 -6
  49. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  50. package/dist/types/src/session/version-pin.d.ts +3 -3
  51. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  52. package/dist/types/src/testing/index.d.ts +2 -0
  53. package/dist/types/src/testing/index.d.ts.map +1 -0
  54. package/dist/types/src/testing/layer.d.ts +22 -0
  55. package/dist/types/src/testing/layer.d.ts.map +1 -0
  56. package/dist/types/src/types/artifact.d.ts +14 -2
  57. package/dist/types/src/types/artifact.d.ts.map +1 -1
  58. package/dist/types/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +40 -31
  60. package/src/conversation/context.test.ts +46 -0
  61. package/src/conversation/context.ts +211 -67
  62. package/src/conversation/conversation.test.ts +65 -0
  63. package/src/conversation/conversation.ts +128 -53
  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 +45 -43
  68. package/src/execution-graph.ts +23 -14
  69. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +2 -2
  70. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +44 -54
  71. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +15 -14
  72. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +36 -44
  73. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +10 -5
  74. package/src/extraction/extraction.ts +9 -8
  75. package/src/extraction/quotes.ts +4 -5
  76. package/src/functions/services.ts +66 -37
  77. package/src/functions.conversations.json +1 -0
  78. package/src/functions.test.ts +74 -0
  79. package/src/session/GenericToolkit.ts +160 -0
  80. package/src/session/artifact-diff.ts +1 -1
  81. package/src/session/format.test.ts +103 -39
  82. package/src/session/format.ts +17 -16
  83. package/src/session/index.ts +3 -0
  84. package/src/session/observer.ts +5 -3
  85. package/src/session/session.conversations.json +1 -1
  86. package/src/session/session.test.ts +28 -15
  87. package/src/session/session.ts +44 -21
  88. package/src/session/toolkit.ts +13 -22
  89. package/src/session/version-pin.ts +6 -6
  90. package/src/templates/{format.tpl → instructions/format.tpl} +1 -4
  91. package/src/templates/system.ts +2 -2
  92. package/src/testing/index.ts +5 -0
  93. package/src/testing/layer.ts +84 -0
  94. package/src/types/artifact.ts +43 -6
  95. package/dist/lib/browser/chunk-CWGVG235.mjs +0 -380
  96. package/dist/lib/browser/chunk-CWGVG235.mjs.map +0 -7
  97. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  98. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  99. package/dist/lib/browser/extraction/index.mjs +0 -272
  100. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  101. package/dist/lib/browser/index.mjs.map +0 -7
  102. package/dist/lib/browser/meta.json +0 -1
  103. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  104. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  105. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  106. package/dist/lib/node-esm/chunk-OV5PMQPB.mjs +0 -382
  107. package/dist/lib/node-esm/chunk-OV5PMQPB.mjs.map +0 -7
  108. package/dist/lib/node-esm/extraction/index.mjs +0 -273
  109. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  110. package/dist/lib/node-esm/index.mjs +0 -934
  111. package/dist/lib/node-esm/index.mjs.map +0 -7
  112. package/dist/lib/node-esm/meta.json +0 -1
  113. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  114. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +0 -7
  115. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  116. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  117. package/src/summarization/summarization.test.ts +0 -202
  118. /package/dist/lib/{browser/named-entity-recognition-QPYHML66.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
  119. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
  120. /package/src/templates/{system.tpl → instructions/system.tpl} +0 -0
@@ -1,934 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- AiAssistantError,
4
- AiModelError,
5
- AiSession,
6
- ArtifactDiffResolver,
7
- GenerationObserver,
8
- VersionPin,
9
- createToolkit
10
- } from "./chunk-OV5PMQPB.mjs";
11
-
12
- // src/conversation/context.ts
13
- import { computed } from "@preact/signals-core";
14
- import * as Array2 from "effect/Array";
15
- import * as Context from "effect/Context";
16
- import * as Function from "effect/Function";
17
- import * as Schema from "effect/Schema";
18
- import { Blueprint } from "@dxos/blueprints";
19
- import { Resource } from "@dxos/context";
20
- import { DXN, Filter, Obj, Query, Type } from "@dxos/echo";
21
- import { invariant } from "@dxos/invariant";
22
- import { ComplexSet } from "@dxos/util";
23
- function _define_property(obj, key, value) {
24
- if (key in obj) {
25
- Object.defineProperty(obj, key, {
26
- value,
27
- enumerable: true,
28
- configurable: true,
29
- writable: true
30
- });
31
- } else {
32
- obj[key] = value;
33
- }
34
- return obj;
35
- }
36
- var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/conversation/context.ts";
37
- var ContextBinding = Schema.Struct({
38
- blueprints: Schema.Struct({
39
- added: Schema.Array(Type.Ref(Blueprint.Blueprint)),
40
- removed: Schema.Array(Type.Ref(Blueprint.Blueprint))
41
- }),
42
- // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)
43
- objects: Schema.Struct({
44
- added: Schema.Array(Type.Ref(Type.Expando)),
45
- removed: Schema.Array(Type.Ref(Type.Expando))
46
- })
47
- }).pipe(Type.Obj({
48
- typename: "dxos.org/type/ContextBinding",
49
- version: "0.1.0"
50
- }));
51
- var Bindings = class {
52
- toJSON() {
53
- return {
54
- blueprints: Array2.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
55
- objects: Array2.fromIterable(this.objects).map((ref) => ref.dxn.toString())
56
- };
57
- }
58
- constructor() {
59
- _define_property(this, "blueprints", new ComplexSet((ref) => ref.dxn.toString()));
60
- _define_property(this, "objects", new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId));
61
- }
62
- };
63
- var AiContextBinder = class extends Resource {
64
- get bindings() {
65
- invariant(this._bindings, "AiContextBinder not open", {
66
- F: __dxlog_file,
67
- L: 78,
68
- S: this,
69
- A: [
70
- "this._bindings",
71
- "'AiContextBinder not open'"
72
- ]
73
- });
74
- return this._bindings;
75
- }
76
- get blueprints() {
77
- invariant(this._blueprints, "AiContextBinder not open", {
78
- F: __dxlog_file,
79
- L: 83,
80
- S: this,
81
- A: [
82
- "this._blueprints",
83
- "'AiContextBinder not open'"
84
- ]
85
- });
86
- return this._blueprints;
87
- }
88
- get objects() {
89
- invariant(this._objects, "AiContextBinder not open", {
90
- F: __dxlog_file,
91
- L: 88,
92
- S: this,
93
- A: [
94
- "this._objects",
95
- "'AiContextBinder not open'"
96
- ]
97
- });
98
- return this._objects;
99
- }
100
- // TODO(wittjosiah): Use parent context?
101
- async _open() {
102
- const query = this._queue.query(Query.select(Filter.everything()));
103
- this._ctx.onDispose(query.subscribe(() => {
104
- }));
105
- this._bindings = computed(() => this._reduce(query.objects));
106
- this._blueprints = computed(() => [
107
- ...this.bindings.value.blueprints
108
- ]);
109
- this._objects = computed(() => [
110
- ...this.bindings.value.objects
111
- ]);
112
- }
113
- async _close() {
114
- this._bindings = void 0;
115
- this._blueprints = void 0;
116
- this._objects = void 0;
117
- }
118
- /**
119
- * Asynchronous query of all bindings.
120
- */
121
- async query() {
122
- const { objects } = await this._queue.query(Query.select(Filter.everything())).run();
123
- return this._reduce(objects);
124
- }
125
- // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.
126
- async bind(props) {
127
- const blueprints = props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ?? [];
128
- const objects = props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];
129
- if (!blueprints.length && !objects.length) {
130
- return;
131
- }
132
- await this._queue.append([
133
- Obj.make(ContextBinding, {
134
- blueprints: {
135
- added: blueprints,
136
- removed: []
137
- },
138
- objects: {
139
- added: objects,
140
- removed: []
141
- }
142
- })
143
- ]);
144
- }
145
- async unbind(props) {
146
- if (!props.blueprints?.length && !props.objects?.length) {
147
- return;
148
- }
149
- await this._queue.append([
150
- Obj.make(ContextBinding, {
151
- blueprints: {
152
- added: [],
153
- removed: props.blueprints ?? []
154
- },
155
- objects: {
156
- added: [],
157
- removed: props.objects ?? []
158
- }
159
- })
160
- ]);
161
- }
162
- _reduce(items) {
163
- return Function.pipe(items, Array2.filter(Obj.instanceOf(ContextBinding)), Array2.reduce(new Bindings(), (context, item) => {
164
- item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
165
- item.blueprints.added.forEach((ref) => context.blueprints.add(ref));
166
- item.objects.removed.forEach((ref) => {
167
- for (const obj of context.objects) {
168
- if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {
169
- context.objects.delete(obj);
170
- }
171
- }
172
- });
173
- item.objects.added.forEach((ref) => context.objects.add(ref));
174
- return context;
175
- }));
176
- }
177
- constructor(_queue) {
178
- super(), _define_property(this, "_queue", void 0), /**
179
- * Reactive query of all bindings.
180
- */
181
- // TODO(burdon): Cache value?
182
- _define_property(this, "_bindings", void 0), _define_property(this, "_blueprints", void 0), _define_property(this, "_objects", void 0), this._queue = _queue;
183
- }
184
- };
185
- var AiContextService = class extends Context.Tag("@dxos/assistant/AiContextService")() {
186
- };
187
-
188
- // src/conversation/conversation.ts
189
- import * as Array4 from "effect/Array";
190
- import * as Effect from "effect/Effect";
191
- import * as Option from "effect/Option";
192
- import { Resource as Resource2 } from "@dxos/context";
193
- import { Obj as Obj2 } from "@dxos/echo";
194
- import { DatabaseService } from "@dxos/functions";
195
- import { log } from "@dxos/log";
196
- import { DataType } from "@dxos/schema";
197
- function _define_property2(obj, key, value) {
198
- if (key in obj) {
199
- Object.defineProperty(obj, key, {
200
- value,
201
- enumerable: true,
202
- configurable: true,
203
- writable: true
204
- });
205
- } else {
206
- obj[key] = value;
207
- }
208
- return obj;
209
- }
210
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/conversation/conversation.ts";
211
- var AiConversation = class extends Resource2 {
212
- async _open() {
213
- await this._context.open();
214
- }
215
- async _close() {
216
- await this._context.close();
217
- }
218
- get context() {
219
- return this._context;
220
- }
221
- get toolkit() {
222
- return this._toolkit;
223
- }
224
- async getHistory() {
225
- const queueItems = await this._queue.queryObjects();
226
- return queueItems.filter(Obj2.instanceOf(DataType.Message));
227
- }
228
- /**
229
- * Creates a new cancelable request effect.
230
- */
231
- createRequest(params) {
232
- return Effect.gen(this, function* () {
233
- const session = new AiSession();
234
- const history = yield* Effect.promise(() => this.getHistory());
235
- const context = yield* Effect.promise(() => this.context.query());
236
- const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(Effect.map(Array4.filter(Option.isSome)), Effect.map(Array4.map((option) => option.value)));
237
- const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(Effect.map(Array4.filter(Option.isSome)), Effect.map(Array4.map((option) => option.value)));
238
- const toolkit = yield* createToolkit({
239
- blueprints
240
- });
241
- this._toolkit = toolkit;
242
- const start = Date.now();
243
- log("run", {
244
- history: history.length,
245
- blueprints: blueprints.length,
246
- objects: objects.length,
247
- tools: this._toolkit?.tools.length ?? 0
248
- }, {
249
- F: __dxlog_file2,
250
- L: 107,
251
- S: this,
252
- C: (f, a) => f(...a)
253
- });
254
- const messages = yield* session.run({
255
- history,
256
- blueprints,
257
- objects,
258
- toolkit,
259
- ...params
260
- }).pipe(Effect.provideService(AiContextService, {
261
- binder: this.context
262
- }));
263
- log("result", {
264
- messages: messages.length,
265
- duration: Date.now() - start
266
- }, {
267
- F: __dxlog_file2,
268
- L: 121,
269
- S: this,
270
- C: (f, a) => f(...a)
271
- });
272
- yield* Effect.promise(() => this._queue.append(messages));
273
- return messages;
274
- }).pipe(Effect.withSpan("AiConversation.request"));
275
- }
276
- constructor(queue) {
277
- super(), /**
278
- * Message and binding queue.
279
- */
280
- _define_property2(this, "_queue", void 0), /**
281
- * Blueprints bound to the conversation.
282
- */
283
- _define_property2(this, "_context", void 0), /**
284
- * Toolkit from the current session request.
285
- */
286
- _define_property2(this, "_toolkit", void 0);
287
- this._queue = queue;
288
- this._context = new AiContextBinder(this._queue);
289
- }
290
- };
291
-
292
- // src/diff.ts
293
- import { next as A } from "@automerge/automerge";
294
- import { DocAccessor, toCursorRange } from "@dxos/echo-db";
295
- import { log as log2 } from "@dxos/log";
296
- import { isNonNullable } from "@dxos/util";
297
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
298
- var reduceDiffs = (diffs) => {
299
- return diffs.reduce((acc, diff) => {
300
- const current = acc[acc.length - 1];
301
- const [op, ...rest] = diff.split(" ");
302
- switch (op) {
303
- case "-": {
304
- if (current && !current.match) {
305
- current.match += rest.join(" ");
306
- } else {
307
- acc.push({
308
- match: rest.join(" "),
309
- replace: ""
310
- });
311
- }
312
- return acc;
313
- }
314
- case "+": {
315
- if (current && !current.replace) {
316
- current.replace += rest.join(" ");
317
- } else {
318
- acc.push({
319
- match: "",
320
- replace: rest.join(" ")
321
- });
322
- }
323
- return acc;
324
- }
325
- }
326
- return acc;
327
- }, []);
328
- };
329
- var computeDiffsWithCursors = (accessor, diffs) => {
330
- return reduceDiffs(diffs).map((diff) => {
331
- const text = DocAccessor.getValue(accessor);
332
- const idx = text.indexOf(diff.match);
333
- if (idx !== -1) {
334
- return {
335
- cursor: toCursorRange(accessor, idx, idx + diff.match.length),
336
- text: diff.replace
337
- };
338
- }
339
- }).filter(isNonNullable);
340
- };
341
- var applyDiffs = (accessor, diffs) => {
342
- for (const diff of reduceDiffs(diffs)) {
343
- accessor.handle.change((doc) => {
344
- const text = DocAccessor.getValue(accessor);
345
- const idx = text.indexOf(diff.match);
346
- if (idx !== -1) {
347
- A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
348
- } else {
349
- log2.warn("diff not found", diff, {
350
- F: __dxlog_file3,
351
- L: 73,
352
- S: void 0,
353
- C: (f, a) => f(...a)
354
- });
355
- }
356
- });
357
- }
358
- return DocAccessor.getValue(accessor);
359
- };
360
-
361
- // src/execution-graph.ts
362
- import { AgentStatus } from "@dxos/ai";
363
- import { Obj as Obj3 } from "@dxos/echo";
364
- import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
365
- import { LogLevel } from "@dxos/log";
366
- import { ContentBlock, DataType as DataType2 } from "@dxos/schema";
367
- import { isNonNullable as isNonNullable2 } from "@dxos/util";
368
- function _define_property3(obj, key, value) {
369
- if (key in obj) {
370
- Object.defineProperty(obj, key, {
371
- value,
372
- enumerable: true,
373
- configurable: true,
374
- writable: true
375
- });
376
- } else {
377
- obj[key] = value;
378
- }
379
- return obj;
380
- }
381
- var ExecutionGraph = class {
382
- /**
383
- * Adds events to the graph.
384
- */
385
- addEvents(events) {
386
- const sortedEvents = this.sortObjectsByCreated(events);
387
- for (const event of sortedEvents) {
388
- if (Obj3.instanceOf(DataType2.Message, event)) {
389
- this._processMessage(event);
390
- } else if (Obj3.instanceOf(AgentStatus, event)) {
391
- this._processAgentStatus(event);
392
- }
393
- }
394
- }
395
- /**
396
- * Processes a message event and creates commits for its blocks.
397
- */
398
- _processMessage(message) {
399
- const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch);
400
- this._commits.push(...messageCommits);
401
- messageCommits.forEach((commit) => this._branchNames.add(commit.branch));
402
- this._trackToolCalls(messageCommits);
403
- if (messageCommits.length > 0) {
404
- this._lastBlockId = messageCommits[messageCommits.length - 1].id;
405
- }
406
- }
407
- /**
408
- * Processes an AgentStatus event.
409
- */
410
- _processAgentStatus(event) {
411
- const branch = this._getToolCallBranch(event.parentMessage, event.toolCallId);
412
- this._branchNames.add(branch);
413
- const agentStatusCommit = {
414
- id: event.id,
415
- branch,
416
- message: event.message,
417
- icon: "ph--flag--regular",
418
- parents: this._getAgentStatusParents(event),
419
- timestamp: new Date(event.created)
420
- };
421
- this._commits.push(agentStatusCommit);
422
- this._lastBlockId = event.id;
423
- if (event.toolCallId) {
424
- this._lastCommitByBranch.set(branch, event.id);
425
- this._updatePendingToolResults(event.toolCallId, event.id);
426
- }
427
- }
428
- /**
429
- * Stable sort: objects with 'created' field are sorted by it, others remain in place.
430
- */
431
- sortObjectsByCreated(objects) {
432
- const sortedObjects = objects.slice();
433
- const createdObjects = [];
434
- sortedObjects.forEach((obj, idx) => {
435
- if (obj && typeof obj.created === "string") {
436
- createdObjects.push({
437
- idx,
438
- obj
439
- });
440
- }
441
- });
442
- createdObjects.sort((a, b) => {
443
- const aDate = new Date(a.obj.created).getTime();
444
- const bDate = new Date(b.obj.created).getTime();
445
- return aDate - bDate;
446
- });
447
- let createdIdx = 0;
448
- return sortedObjects.map((obj, _idx) => {
449
- if (obj && typeof obj.created === "string") {
450
- return createdObjects[createdIdx++].obj;
451
- }
452
- return obj;
453
- });
454
- }
455
- /**
456
- * Returns the current state of the graph.
457
- */
458
- getGraph(lastRequest = false) {
459
- const idx = lastRequest ? this._commits.findLastIndex((c) => c.tags?.includes("user")) : -1;
460
- const commits = idx === -1 ? this._commits : this._commits.slice(idx);
461
- return {
462
- branches: Array.from(this._branchNames),
463
- commits
464
- };
465
- }
466
- /**
467
- * Tracks tool calls and handles pending tool result updates.
468
- */
469
- _trackToolCalls(commits) {
470
- commits.forEach((commit) => {
471
- if (this._isToolCallCommit(commit)) {
472
- const toolCallId = this._extractToolCallId(commit.id);
473
- if (toolCallId) {
474
- this._toolCallCommitIds.set(toolCallId, commit.id);
475
- }
476
- }
477
- if (this._isToolResultCommit(commit)) {
478
- const toolCallId = this._extractToolCallId(commit.id);
479
- if (toolCallId) {
480
- this._pendingToolResults.set(toolCallId, commit.id);
481
- this._handleLateToolResultUpdate(toolCallId, commit.id);
482
- }
483
- }
484
- this._lastCommitByBranch.set(commit.branch, commit.id);
485
- });
486
- }
487
- /**
488
- * Updates pending tool results to point to an AgentStatus event.
489
- */
490
- _updatePendingToolResults(toolCallId, agentStatusId) {
491
- const toolResultId = this._pendingToolResults.get(toolCallId);
492
- if (!toolResultId) return;
493
- const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
494
- if (!toolResultCommit) return;
495
- const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
496
- if (!toolCallCommitId) return;
497
- const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
498
- if (toolCallIndex !== -1) {
499
- toolResultCommit.parents[toolCallIndex] = agentStatusId;
500
- }
501
- this._pendingToolResults.delete(toolCallId);
502
- }
503
- /**
504
- * Handles late updates when AgentStatus is processed before tool result.
505
- */
506
- _handleLateToolResultUpdate(toolCallId, toolResultId) {
507
- const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
508
- if (!toolCallCommitId) return;
509
- const messageId = toolCallCommitId.split("_toolCall_")[0];
510
- const toolCallBranch = `${messageId}_${toolCallId}`;
511
- const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
512
- if (agentStatusCommitId && agentStatusCommitId !== toolCallCommitId) {
513
- const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
514
- if (toolResultCommit) {
515
- const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
516
- if (toolCallIndex !== -1) {
517
- toolResultCommit.parents[toolCallIndex] = agentStatusCommitId;
518
- }
519
- }
520
- this._pendingToolResults.delete(toolCallId);
521
- }
522
- }
523
- /**
524
- * Gets the branch name for a tool call.
525
- */
526
- _getToolCallBranch(parentMessage, toolCallId) {
527
- if (toolCallId) {
528
- return toolCallId;
529
- }
530
- return parentMessage || "main";
531
- }
532
- /**
533
- * Gets the parents for an AgentStatus commit.
534
- */
535
- _getAgentStatusParents(event) {
536
- if (event.parentMessage && event.toolCallId) {
537
- return [
538
- getToolCallId(event.parentMessage, event.toolCallId)
539
- ];
540
- }
541
- return [];
542
- }
543
- /**
544
- * Checks if a commit is a tool call commit.
545
- */
546
- _isToolCallCommit(commit) {
547
- return commit.message.includes("Calling tool");
548
- }
549
- /**
550
- * Checks if a commit is a tool result commit.
551
- */
552
- _isToolResultCommit(commit) {
553
- return commit.message.includes("Tool call succeeded") || commit.message.includes("Tool error:");
554
- }
555
- /**
556
- * Extracts tool call ID from a commit ID.
557
- */
558
- _extractToolCallId(commitId) {
559
- const toolCallMatch = commitId.match(/_toolCall_(.+)$/);
560
- const toolResultMatch = commitId.match(/_toolResult_(.+)$/);
561
- return toolCallMatch?.[1] || toolResultMatch?.[1];
562
- }
563
- constructor() {
564
- _define_property3(this, "_commits", []);
565
- _define_property3(this, "_branchNames", /* @__PURE__ */ new Set());
566
- _define_property3(this, "_lastBlockId", void 0);
567
- _define_property3(this, "_toolCallCommitIds", /* @__PURE__ */ new Map());
568
- _define_property3(this, "_lastCommitByBranch", /* @__PURE__ */ new Map());
569
- _define_property3(this, "_pendingToolResults", /* @__PURE__ */ new Map());
570
- }
571
- };
572
- var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch) => {
573
- let previousBlockId = lastBlockId;
574
- return message.blocks.map((block, idx) => {
575
- const branch = getMessageBranch(message);
576
- const parents = getBlockParents(block, previousBlockId, message, toolCallIds, lastCommitByBranch);
577
- const commit = createBlockCommit(block, message, branch, parents, idx);
578
- if (commit) {
579
- previousBlockId = commit.id;
580
- }
581
- return commit;
582
- }).filter(isNonNullable2);
583
- };
584
- var getBlockParents = (block, previousBlockId, message, toolCallIds, lastCommitByBranch) => {
585
- const parents = [];
586
- if (block._tag === "toolResult") {
587
- if (previousBlockId) {
588
- parents.push(previousBlockId);
589
- }
590
- const toolCallCommitId = toolCallIds?.get(block.toolCallId);
591
- if (toolCallCommitId) {
592
- const toolCallBranch = getToolCallBranchFromCommitId(toolCallCommitId, block.toolCallId);
593
- const lastBlockFromToolCallBranch = lastCommitByBranch?.get(toolCallBranch);
594
- if (lastBlockFromToolCallBranch) {
595
- parents.push(lastBlockFromToolCallBranch);
596
- } else {
597
- parents.push(toolCallCommitId);
598
- }
599
- }
600
- } else {
601
- if (previousBlockId) {
602
- parents.push(previousBlockId);
603
- } else {
604
- const toolCallParent = getParentId(message);
605
- if (toolCallParent) {
606
- parents.push(toolCallParent);
607
- }
608
- }
609
- }
610
- return parents;
611
- };
612
- var createBlockCommit = (block, message, branch, parents, idx) => {
613
- const timestamp = new Date(message.created);
614
- switch (block._tag) {
615
- case "text":
616
- if (!block.text.trim().length) return null;
617
- return {
618
- id: getGenericBlockId(message.id, idx),
619
- branch,
620
- parents,
621
- timestamp,
622
- ...message.sender.role === "user" ? {
623
- icon: "ph--user--regular",
624
- tags: [
625
- "user"
626
- ],
627
- message: "Processing request..."
628
- } : {
629
- icon: "ph--robot--regular",
630
- message: `Response (${block.text.split(" ").length} words)`
631
- }
632
- };
633
- case "toolCall":
634
- return {
635
- id: getToolCallId(message.id, block.toolCallId),
636
- branch,
637
- parents,
638
- timestamp,
639
- icon: "ph--wrench--regular",
640
- level: LogLevel.INFO,
641
- message: `Calling tool (${block.name})`
642
- };
643
- case "toolResult":
644
- return {
645
- id: getToolResultId(message.id, block.toolCallId),
646
- branch,
647
- parents,
648
- timestamp,
649
- icon: block.error ? "ph--x-circle--regular" : "ph--check-circle--regular",
650
- level: block.error ? LogLevel.ERROR : LogLevel.INFO,
651
- message: block.error ? "Tool error: " + block.error : "Tool call succeeded"
652
- };
653
- case "summary":
654
- return {
655
- id: getGenericBlockId(message.id, idx),
656
- branch,
657
- parents,
658
- timestamp,
659
- icon: "ph--rocket--regular",
660
- level: LogLevel.INFO,
661
- message: ContentBlock.createSummaryMessage(block)
662
- };
663
- case "status":
664
- return {
665
- id: getGenericBlockId(message.id, idx),
666
- branch,
667
- parents,
668
- timestamp,
669
- message: block.statusText,
670
- level: LogLevel.INFO,
671
- icon: "ph--flag--regular"
672
- };
673
- case "reasoning":
674
- return {
675
- id: getGenericBlockId(message.id, idx),
676
- branch,
677
- parents,
678
- timestamp,
679
- message: block.reasoningText ?? "Thinking...",
680
- icon: "ph--brain--regular"
681
- };
682
- case "reference":
683
- return {
684
- id: getGenericBlockId(message.id, idx),
685
- branch,
686
- parents,
687
- timestamp,
688
- icon: "ph--link--regular",
689
- message: stringifyRef(block.reference)
690
- };
691
- default:
692
- return null;
693
- }
694
- };
695
- var getToolCallBranchFromCommitId = (toolCallCommitId, toolCallId) => {
696
- const messageId = toolCallCommitId.split("_toolCall_")[0];
697
- return `${messageId}_${toolCallId}`;
698
- };
699
- var getToolCallId = (messageId, toolCallId) => `${messageId}_toolCall_${toolCallId}`;
700
- var getToolResultId = (messageId, toolCallId) => `${messageId}_toolResult_${toolCallId}`;
701
- var getGenericBlockId = (messageId, idx) => `${messageId}_block_${idx}`;
702
- var getBranchName = (options) => {
703
- if (options.toolCallId) {
704
- return options.toolCallId;
705
- } else if (options.parentMessage) {
706
- return options.parentMessage;
707
- } else {
708
- return "main";
709
- }
710
- };
711
- var getMessageBranch = (message) => {
712
- return getBranchName({
713
- parentMessage: message.parentMessage,
714
- toolCallId: message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]
715
- });
716
- };
717
- var getParentId = (message) => {
718
- if (message.parentMessage && message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]) {
719
- return getToolCallId(message.parentMessage, message.properties[MESSAGE_PROPERTY_TOOL_CALL_ID]);
720
- } else {
721
- return void 0;
722
- }
723
- };
724
- var stringifyRef = (ref) => {
725
- if (ref.target) {
726
- return stringifyObject(ref.target);
727
- }
728
- return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
729
- };
730
- var stringifyObject = (obj) => {
731
- return Obj3.getLabel(obj) ?? Obj3.getTypename(obj) ?? obj.id;
732
- };
733
-
734
- // src/functions/services.ts
735
- import * as Tool from "@effect/ai/Tool";
736
- import * as Context2 from "effect/Context";
737
- import * as Effect2 from "effect/Effect";
738
- import * as Layer from "effect/Layer";
739
- import * as Record from "effect/Record";
740
- import * as Schema2 from "effect/Schema";
741
- import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from "@dxos/ai";
742
- import { todo } from "@dxos/debug";
743
- import { Query as Query2 } from "@dxos/echo";
744
- import { DatabaseService as DatabaseService2, FunctionDefinition, FunctionInvocationService, FunctionType } from "@dxos/functions";
745
- import { invariant as invariant2 } from "@dxos/invariant";
746
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/assistant/src/functions/services.ts";
747
- var makeToolResolverFromFunctions = (functions, toolkit) => {
748
- return Layer.effect(ToolResolverService, Effect2.gen(function* () {
749
- const dbService = yield* DatabaseService2;
750
- return {
751
- resolve: (id) => Effect2.gen(function* () {
752
- const tool = toolkit.tools[id];
753
- if (tool) {
754
- return tool;
755
- }
756
- const { objects: [dbFunction] } = yield* DatabaseService2.runQuery(Query2.type(FunctionType, {
757
- key: id
758
- }));
759
- const functionDef = dbFunction ? FunctionDefinition.deserialize(dbFunction) : functions.find((fn2) => fn2.key === id);
760
- if (!functionDef) {
761
- return yield* Effect2.fail(new AiToolNotFoundError(id));
762
- }
763
- return projectFunctionToTool(functionDef);
764
- }).pipe(Effect2.provideService(DatabaseService2, dbService))
765
- };
766
- }));
767
- };
768
- var makeToolExecutionServiceFromFunctions = (toolkit, handlersLayer) => {
769
- return Layer.effect(ToolExecutionService, Effect2.gen(function* () {
770
- const toolkitHandler = yield* toolkit.pipe(Effect2.provide(handlersLayer));
771
- invariant2(isHandlerLike(toolkitHandler), void 0, {
772
- F: __dxlog_file4,
773
- L: 73,
774
- S: this,
775
- A: [
776
- "isHandlerLike(toolkitHandler)",
777
- ""
778
- ]
779
- });
780
- const functionInvocationService = yield* FunctionInvocationService;
781
- return {
782
- handlersFor: (toolkit2) => {
783
- const makeHandler = (tool) => {
784
- return Effect2.fn(`toolFunctionHandler ${tool.name}`)(function* (input) {
785
- if (toolkitHandler.tools[tool.name]) {
786
- if (Tool.isProviderDefined(tool)) {
787
- throw new Error("Attempted to call a provider-defined tool");
788
- }
789
- return yield* toolkitHandler.handle(tool.name, input);
790
- }
791
- const { definition: functionDef } = Context2.get(FunctionToolAnnotation)(tool.annotations);
792
- return yield* functionInvocationService.invokeFunction(functionDef, input).pipe(Effect2.catchAllDefect((defect) => Effect2.fail(defect)));
793
- });
794
- };
795
- return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
796
- }
797
- };
798
- }));
799
- };
800
- var FunctionToolAnnotation = class extends Context2.Tag("@dxos/assistant/FunctionToolAnnotation")() {
801
- };
802
- var toolCache = /* @__PURE__ */ new WeakMap();
803
- var projectFunctionToTool = (fn2) => {
804
- if (toolCache.has(fn2)) {
805
- return toolCache.get(fn2);
806
- }
807
- const tool = Tool.make(makeToolName(fn2.name), {
808
- description: fn2.description,
809
- parameters: createStructFieldsFromSchema(fn2.inputSchema),
810
- // TODO(dmaretskyi): Include output schema.
811
- failure: Schema2.Any
812
- }).annotate(FunctionToolAnnotation, {
813
- definition: fn2
814
- });
815
- toolCache.set(fn2, tool);
816
- return tool;
817
- };
818
- var makeToolName = (name) => {
819
- const toolName = name.replace(/[^a-zA-Z0-9]/g, "_");
820
- invariant2(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/), void 0, {
821
- F: __dxlog_file4,
822
- L: 140,
823
- S: void 0,
824
- A: [
825
- "toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/)",
826
- ""
827
- ]
828
- });
829
- return toolName;
830
- };
831
- var createStructFieldsFromSchema = (schema) => {
832
- switch (schema.ast._tag) {
833
- case "TypeLiteral":
834
- return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
835
- prop.name,
836
- Schema2.make(prop.type)
837
- ]));
838
- case "VoidKeyword":
839
- return {};
840
- default:
841
- return todo(`Unsupported schema AST: ${schema.ast._tag}`);
842
- }
843
- };
844
- var isHandlerLike = (value) => {
845
- return typeof value.tools === "object" && typeof value.handle === "function";
846
- };
847
-
848
- // src/templates/system.ts
849
- import defaultsDeep from "lodash.defaultsdeep";
850
- import { Template } from "@dxos/blueprints";
851
-
852
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw
853
- var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\n\n### Multiple choice questions\n\nYou may ask multiple choice questions by wrapping consise options inside <option> tags inside a well formed <select> tag.\nExample: <select><option>Yes</option><option>No</option></select>\n\n## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
854
-
855
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw
856
- var system_default = "{{! System Prompt }}\n\n- You are a helpful assistant called Kai. \n- Your name is Kai and you are powered by different language models.\n- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.\n- In your initial greeting state your name and make some suggestions based on the current context objects.\n- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\n- Your task is to process user commands and questions and decide how best to respond.\n- In general be concise and direct.\n- Follow all instructions carefully.\n\n## Planning\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints and Artifacts\n\n- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.\n- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.\n- If it is ambiguous, query for existing artifacts first and then decide.\n- If you decide to create an artifact, call the associated tool to create the artifact.\n- Artifacts are stored in the database. Tools are used to create and query artifacts.\n- If you are unsure about creating an artifact ask the user for clarification.\n- Artifacts are mutable objects that can change over the course of the conversation.\n- Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.\n- You must never generate the id of the artifact; only recall the ids that are already in the history.\n- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.\n- You can add suggested actions at the end of your response.\n- Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.\n- Suggested actions must be in the form of a user instruction that you can follow.\n- Suggested actions could include actions that create artifacts.\n- After creating an artifact use a tool to add it to the chat context.\n\n## Context\n\nToday is {{DATETIME}}.\n";
857
-
858
- // src/templates/system.ts
859
- var createSystemPrompt = (options = {}) => Template.process(format_default, defaultsDeep(options, {
860
- DATETIME: (/* @__PURE__ */ new Date()).toISOString()
861
- }));
862
- var templates = {
863
- /** Editable system prompt.*/
864
- system: Template.make({
865
- /**
866
- * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
867
- */
868
- id: "01K2J2FZWH39F55CS7B26GP1Q3",
869
- source: system_default
870
- })
871
- };
872
-
873
- // src/types/artifact.ts
874
- import * as Schema3 from "effect/Schema";
875
- import { DXN as DXN2, LOCAL_SPACE_TAG } from "@dxos/keys";
876
- import { trim } from "@dxos/util";
877
- var createArtifactElement = (id) => `<artifact id=${id} />`;
878
- var ArtifactId = class extends Schema3.String.annotations({
879
- description: trim`
880
- The ID of the referenced object. Formats accepted:
881
- - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
882
- - space ID, object ID tuple (spaceID:objectID)
883
- - Only object ID that is assumed to be in the current space (XXXXX)
884
- `,
885
- examples: [
886
- "dxn:echo:@:XXXXX",
887
- "@dxn:echo:@:XXXXX",
888
- "spaceID:objectID",
889
- "XXXXX"
890
- ]
891
- }) {
892
- static toDXN(reference, owningSpaceId) {
893
- if (reference.startsWith("@dxn:")) {
894
- return DXN2.parse(reference.slice(1));
895
- } else if (reference.startsWith("dxn:")) {
896
- return DXN2.parse(reference);
897
- } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {
898
- const [spaceId, objectId] = reference.split(":");
899
- return new DXN2(DXN2.kind.ECHO, [
900
- spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId,
901
- objectId
902
- ]);
903
- } else if (/^[A-Z0-9]+$/.test(reference)) {
904
- return DXN2.fromLocalObjectId(reference);
905
- } else {
906
- throw new Error(`Unable to parse object reference: ${reference}`);
907
- }
908
- }
909
- };
910
- export {
911
- AiAssistantError,
912
- AiContextBinder,
913
- AiContextService,
914
- AiConversation,
915
- AiModelError,
916
- AiSession,
917
- ArtifactDiffResolver,
918
- ArtifactId,
919
- Bindings,
920
- ContextBinding,
921
- ExecutionGraph,
922
- GenerationObserver,
923
- VersionPin,
924
- applyDiffs,
925
- computeDiffsWithCursors,
926
- createArtifactElement,
927
- createSystemPrompt,
928
- createToolkit,
929
- makeToolExecutionServiceFromFunctions,
930
- makeToolResolverFromFunctions,
931
- reduceDiffs,
932
- templates
933
- };
934
- //# sourceMappingURL=index.mjs.map