@dxos/assistant 0.8.4-main.74a063c4e0 → 0.8.4-main.765dc60934

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 (145) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +1 -1
  3. package/dist/lib/neutral/extraction/index.mjs +7 -22
  4. package/dist/lib/neutral/extraction/index.mjs.map +3 -3
  5. package/dist/lib/neutral/index.mjs +1287 -83
  6. package/dist/lib/neutral/index.mjs.map +4 -4
  7. package/dist/lib/neutral/meta.json +1 -1
  8. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  9. package/dist/types/src/extraction/extraction.d.ts +461 -455
  10. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  11. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  12. package/dist/types/src/functions/services.d.ts +7 -29
  13. package/dist/types/src/functions/services.d.ts.map +1 -1
  14. package/dist/types/src/index.d.ts +2 -7
  15. package/dist/types/src/index.d.ts.map +1 -1
  16. package/dist/types/src/{session/session.d.ts → request/AiRequest.d.ts} +26 -34
  17. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  18. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  19. package/dist/types/src/request/format.d.ts +15 -0
  20. package/dist/types/src/request/format.d.ts.map +1 -0
  21. package/dist/types/src/request/index.d.ts +4 -0
  22. package/dist/types/src/request/index.d.ts.map +1 -0
  23. package/dist/types/src/{session → request}/observer.d.ts.map +1 -1
  24. package/dist/types/src/{session → request}/version-pin.d.ts.map +1 -1
  25. package/dist/types/src/{conversation/context.d.ts → session/AiContext.d.ts} +22 -23
  26. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  27. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  28. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  29. package/dist/types/src/session/AiSession.d.ts +73 -0
  30. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  31. package/dist/types/src/session/index.d.ts +2 -5
  32. package/dist/types/src/session/index.d.ts.map +1 -1
  33. package/dist/types/src/session/toolkit.d.ts +5 -7
  34. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  35. package/dist/types/src/templates/system.d.ts +1 -1
  36. package/dist/types/src/templates/system.d.ts.map +1 -1
  37. package/dist/types/src/{types → util}/artifact.d.ts +1 -2
  38. package/dist/types/src/util/artifact.d.ts.map +1 -0
  39. package/dist/types/src/util/diff.d.ts.map +1 -0
  40. package/dist/types/src/{diff.test.d.ts.map → util/diff.test.d.ts.map} +1 -1
  41. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  42. package/dist/types/src/{errors.d.ts → util/errors.d.ts} +12 -12
  43. package/dist/types/src/util/errors.d.ts.map +1 -0
  44. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  45. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  46. package/dist/types/src/util/index.d.ts +7 -0
  47. package/dist/types/src/util/index.d.ts.map +1 -0
  48. package/dist/types/src/{tracing.d.ts → util/tracing.d.ts} +64 -95
  49. package/dist/types/src/util/tracing.d.ts.map +1 -0
  50. package/dist/types/tsconfig.tsbuildinfo +1 -1
  51. package/package.json +23 -40
  52. package/src/extraction/extraction.ts +1 -1
  53. package/src/functions/services.ts +13 -128
  54. package/src/index.ts +2 -7
  55. package/src/{session/session.ts → request/AiRequest.ts} +52 -53
  56. package/src/{session → request}/format.ts +15 -10
  57. package/src/request/index.ts +8 -0
  58. package/src/{conversation/context.test.ts → session/AiContext.test.ts} +4 -3
  59. package/src/{conversation/context.ts → session/AiContext.ts} +24 -24
  60. package/src/session/AiSession.ts +324 -0
  61. package/src/session/index.ts +3 -5
  62. package/src/session/toolkit.ts +18 -15
  63. package/src/templates/instructions/system.tpl +40 -1
  64. package/src/templates/system.ts +1 -1
  65. package/src/{types → util}/artifact.ts +2 -3
  66. package/src/{session → util}/error-handling.ts +3 -2
  67. package/src/{execution-graph.ts → util/execution-graph.ts} +16 -6
  68. package/src/util/index.ts +10 -0
  69. package/src/util/tracing.ts +57 -0
  70. package/dist/lib/neutral/chunk-UAWIXKF6.mjs +0 -1875
  71. package/dist/lib/neutral/chunk-UAWIXKF6.mjs.map +0 -7
  72. package/dist/lib/neutral/testing/index.mjs +0 -114
  73. package/dist/lib/neutral/testing/index.mjs.map +0 -7
  74. package/dist/types/src/conversation/context.d.ts.map +0 -1
  75. package/dist/types/src/conversation/context.test.d.ts +0 -2
  76. package/dist/types/src/conversation/context.test.d.ts.map +0 -1
  77. package/dist/types/src/conversation/conversation.d.ts +0 -68
  78. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  79. package/dist/types/src/conversation/conversation.test.d.ts +0 -2
  80. package/dist/types/src/conversation/conversation.test.d.ts.map +0 -1
  81. package/dist/types/src/conversation/index.d.ts +0 -3
  82. package/dist/types/src/conversation/index.d.ts.map +0 -1
  83. package/dist/types/src/diff.d.ts.map +0 -1
  84. package/dist/types/src/errors.d.ts.map +0 -1
  85. package/dist/types/src/execution-graph.d.ts.map +0 -1
  86. package/dist/types/src/execution-graph.test.d.ts.map +0 -1
  87. package/dist/types/src/functions.test.d.ts +0 -2
  88. package/dist/types/src/functions.test.d.ts.map +0 -1
  89. package/dist/types/src/service/AgentService.d.ts +0 -61
  90. package/dist/types/src/service/AgentService.d.ts.map +0 -1
  91. package/dist/types/src/service/AgentService.test.d.ts +0 -2
  92. package/dist/types/src/service/AgentService.test.d.ts.map +0 -1
  93. package/dist/types/src/service/agent-process.d.ts +0 -17
  94. package/dist/types/src/service/agent-process.d.ts.map +0 -1
  95. package/dist/types/src/service/index.d.ts +0 -3
  96. package/dist/types/src/service/index.d.ts.map +0 -1
  97. package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
  98. package/dist/types/src/session/error-handling.d.ts.map +0 -1
  99. package/dist/types/src/session/format.d.ts +0 -12
  100. package/dist/types/src/session/format.d.ts.map +0 -1
  101. package/dist/types/src/session/format.test.d.ts +0 -2
  102. package/dist/types/src/session/format.test.d.ts.map +0 -1
  103. package/dist/types/src/session/session.d.ts.map +0 -1
  104. package/dist/types/src/session/session.test.d.ts +0 -2
  105. package/dist/types/src/session/session.test.d.ts.map +0 -1
  106. package/dist/types/src/testing/index.d.ts +0 -2
  107. package/dist/types/src/testing/index.d.ts.map +0 -1
  108. package/dist/types/src/testing/layer.d.ts +0 -35
  109. package/dist/types/src/testing/layer.d.ts.map +0 -1
  110. package/dist/types/src/tracing.d.ts.map +0 -1
  111. package/dist/types/src/types/artifact.d.ts.map +0 -1
  112. package/dist/types/src/types/index.d.ts +0 -2
  113. package/dist/types/src/types/index.d.ts.map +0 -1
  114. package/src/conversation/conversation.test.ts +0 -58
  115. package/src/conversation/conversation.ts +0 -275
  116. package/src/conversation/index.ts +0 -6
  117. package/src/functions.conversations.json +0 -1
  118. package/src/functions.test.ts +0 -82
  119. package/src/service/AgentService.conversations.json +0 -1
  120. package/src/service/AgentService.test.ts +0 -169
  121. package/src/service/AgentService.ts +0 -165
  122. package/src/service/agent-process.ts +0 -359
  123. package/src/service/index.ts +0 -6
  124. package/src/session/format.test.ts +0 -132
  125. package/src/session/session.conversations.json +0 -1
  126. package/src/session/session.test.ts +0 -190
  127. package/src/testing/index.ts +0 -5
  128. package/src/testing/layer.ts +0 -258
  129. package/src/tracing.ts +0 -113
  130. package/src/types/index.ts +0 -5
  131. /package/dist/types/src/{session → request}/artifact-diff.d.ts +0 -0
  132. /package/dist/types/src/{session → request}/observer.d.ts +0 -0
  133. /package/dist/types/src/{session → request}/version-pin.d.ts +0 -0
  134. /package/dist/types/src/{diff.d.ts → util/diff.d.ts} +0 -0
  135. /package/dist/types/src/{diff.test.d.ts → util/diff.test.d.ts} +0 -0
  136. /package/dist/types/src/{session → util}/error-handling.d.ts +0 -0
  137. /package/dist/types/src/{execution-graph.d.ts → util/execution-graph.d.ts} +0 -0
  138. /package/dist/types/src/{execution-graph.test.d.ts → util/execution-graph.test.d.ts} +0 -0
  139. /package/src/{session → request}/artifact-diff.ts +0 -0
  140. /package/src/{session → request}/observer.ts +0 -0
  141. /package/src/{session → request}/version-pin.ts +0 -0
  142. /package/src/{diff.test.ts → util/diff.test.ts} +0 -0
  143. /package/src/{diff.ts → util/diff.ts} +0 -0
  144. /package/src/{errors.ts → util/errors.ts} +0 -0
  145. /package/src/{execution-graph.test.ts → util/execution-graph.test.ts} +0 -0
@@ -1,49 +1,84 @@
1
1
  import {
2
- AGENT_PROCESS_KEY,
3
- AgentInputReceived,
4
- AgentRequestCompleted,
5
- AgentService_exports,
6
- AgentTurnCompleted,
7
- AgentTurnStarted,
8
- AiAssistantError,
9
- AiContextBinder,
10
- AiContextService,
11
- AiConversation,
12
- AiConversationService,
13
- AiModelError,
14
- AiSession,
15
- ArtifactDiffResolver,
16
- ArtifactId,
17
- Bindings,
18
- CompleteBlock,
19
- ContextBinding,
20
- GenerationObserver,
21
- PartialBlock,
22
- RefFromLLM,
23
- ToolCallCompleted,
24
- ToolCallStarted,
25
- ToolExecutionServices,
26
- VersionPin,
27
- createArtifactElement,
28
- createToolkit,
29
- formatSystemPrompt,
30
- formatUserPrompt,
31
- functionInvocationServiceFromOperations,
32
- getOperationFromTool,
33
- makeToolExecutionService,
34
- makeToolExecutionServiceFromFunctions,
35
- makeToolExecutionServiceFromOperationInvoker,
36
- makeToolResolverFromFunctions,
37
- makeToolResolverFromOperations
38
- } from "./chunk-UAWIXKF6.mjs";
39
- import "./chunk-J5LGTIGS.mjs";
2
+ __export
3
+ } from "./chunk-J5LGTIGS.mjs";
4
+
5
+ // src/functions/services.ts
6
+ import * as Tool from "@effect/ai/Tool";
7
+ import * as Context from "effect/Context";
8
+ import * as Effect2 from "effect/Effect";
9
+ import * as Layer from "effect/Layer";
10
+ import * as Option from "effect/Option";
11
+ import * as Record from "effect/Record";
12
+ import * as Schema4 from "effect/Schema";
13
+ import * as SchemaAST from "effect/SchemaAST";
14
+ import { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from "@dxos/ai";
15
+ import { OpaqueToolkit } from "@dxos/ai";
16
+ import { Operation, OperationRegistry } from "@dxos/compute";
17
+ import { todo } from "@dxos/debug";
18
+ import { Ref as Ref2 } from "@dxos/echo";
19
+ import { invariant } from "@dxos/invariant";
20
+
21
+ // src/util/artifact.ts
22
+ import * as Schema from "effect/Schema";
23
+ import { Database, Obj, Ref } from "@dxos/echo";
24
+ import { EncodedReference } from "@dxos/echo-protocol";
25
+ import { DXN, LOCAL_SPACE_TAG } from "@dxos/keys";
26
+ import { trim } from "@dxos/util";
27
+ var createArtifactElement = (id) => `<artifact id=${id} />`;
28
+ var ArtifactId = class extends Schema.String.annotations({
29
+ // TODO(dmaretskyi): This section gets overriden.
30
+ description: trim`
31
+ The ID of the referenced object. Formats accepted:
32
+ - DXN (dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4). DXNs can be prepended with an @ symbol for compatibility with in-text references.
33
+ - space ID, object ID tuple (spaceID:objectID)
34
+ - Only object ID that is assumed to be in the current space (01KG7R1ZXWFMWQ4DA1Q6TN1DG4)
35
+ `,
36
+ examples: [
37
+ "dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
38
+ "@dxn:echo:@:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
39
+ "BM3FSHFOMJCHCG5QW7JTVKGYABD2GAA7G:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
40
+ "01KG7R1ZXWFMWQ4DA1Q6TN1DG4"
41
+ ]
42
+ }) {
43
+ static toDXN(reference, owningSpaceId) {
44
+ if (reference.startsWith("@dxn:")) {
45
+ return DXN.parse(reference.slice(1));
46
+ } else if (reference.startsWith("dxn:")) {
47
+ return DXN.parse(reference);
48
+ } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {
49
+ const [spaceId, objectId] = reference.split(":");
50
+ return new DXN(DXN.kind.ECHO, [
51
+ spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId,
52
+ objectId
53
+ ]);
54
+ } else if (/^[A-Z0-9]+$/.test(reference)) {
55
+ return DXN.fromLocalObjectId(reference);
56
+ } else {
57
+ throw new Error(`Unable to parse object reference: ${reference}`);
58
+ }
59
+ }
60
+ /**
61
+ * Resolves an artifact ID to an object.
62
+ */
63
+ static resolve(schema, ref) {
64
+ const dxn = ArtifactId.toDXN(ref);
65
+ return Database.resolve(dxn, schema);
66
+ }
67
+ };
68
+ var RefFromLLM = Schema.transform(ArtifactId, Ref.Ref(Obj.Unknown), {
69
+ decode: (fromA, fromI) => EncodedReference.fromDXN(ArtifactId.toDXN(fromA)),
70
+ encode: (toI, toA) => EncodedReference.toDXN(toI).toString(),
71
+ strict: false
72
+ }).annotations({
73
+ description: ArtifactId.ast.annotations.description
74
+ });
40
75
 
41
- // src/diff.ts
76
+ // src/util/diff.ts
42
77
  import { next as A } from "@automerge/automerge";
43
78
  import { DocAccessor, toCursorRange } from "@dxos/echo-db";
44
79
  import { log } from "@dxos/log";
45
80
  import { isNonNullable } from "@dxos/util";
46
- var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/diff.ts";
81
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/assistant/src/util/diff.ts";
47
82
  var reduceDiffs = (diffs) => {
48
83
  return diffs.reduce((acc, diff) => {
49
84
  const current = acc[acc.length - 1];
@@ -100,12 +135,7 @@ var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
100
135
  if (errorOnNotFound) {
101
136
  throw new Error(`Diff not found: ${diff.match}`);
102
137
  } else {
103
- log.warn("diff not found", diff, {
104
- F: __dxlog_file,
105
- L: 86,
106
- S: void 0,
107
- C: (f, a) => f(...a)
108
- });
138
+ log.warn("diff not found", diff, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 71, S: void 0 });
109
139
  }
110
140
  }
111
141
  });
@@ -113,9 +143,53 @@ var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
113
143
  return DocAccessor.getValue(accessor);
114
144
  };
115
145
 
116
- // src/execution-graph.ts
146
+ // src/util/error-handling.ts
147
+ import * as AiError from "@effect/ai/AiError";
148
+ import * as HttpClientError from "@effect/platform/HttpClientError";
149
+ import * as Effect from "effect/Effect";
150
+ import * as Schema2 from "effect/Schema";
151
+
152
+ // src/util/errors.ts
153
+ import { BaseError } from "@dxos/errors";
154
+ var AiModelError = class extends BaseError.extend("AiModelError", "AI model error") {
155
+ };
156
+ var AiAssistantError = class extends BaseError.extend("AiAssistantError", "AI assistant error") {
157
+ };
158
+
159
+ // src/util/error-handling.ts
160
+ var AnthropicErrorResponse = Schema2.Struct({
161
+ type: Schema2.Literal("error"),
162
+ error: Schema2.Struct({
163
+ type: Schema2.String,
164
+ message: Schema2.String
165
+ })
166
+ });
167
+ var mapAiError = (err) => Effect.gen(function* () {
168
+ const cause = err.cause;
169
+ if (HttpClientError.isHttpClientError(cause) && cause.reason === "StatusCode") {
170
+ const body = yield* cause.response.json.pipe(Effect.flatMap(Schema2.decodeUnknown(AnthropicErrorResponse, {
171
+ exact: false
172
+ })));
173
+ const parsedCause = new AiModelError({
174
+ message: body.error.message,
175
+ context: {
176
+ model: "anthropic",
177
+ type: body.error.type
178
+ }
179
+ });
180
+ return AiError.UnknownError.make({
181
+ description: body.error.message,
182
+ module: err.module,
183
+ method: err.method,
184
+ cause: parsedCause
185
+ });
186
+ }
187
+ return err;
188
+ }).pipe(Effect.catchAll(() => Effect.succeed(err)));
189
+
190
+ // src/util/execution-graph.ts
117
191
  import { AgentStatus } from "@dxos/ai";
118
- import { Obj } from "@dxos/echo";
192
+ import { Obj as Obj2 } from "@dxos/echo";
119
193
  import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
120
194
  import { LogLevel } from "@dxos/log";
121
195
  import { ContentBlock, Message } from "@dxos/types";
@@ -142,9 +216,9 @@ var ExecutionGraph = class {
142
216
  addEvents(events) {
143
217
  const sortedEvents = this.sortObjectsByCreated(events);
144
218
  for (const event of sortedEvents) {
145
- if (Obj.instanceOf(Message.Message, event)) {
219
+ if (Obj2.instanceOf(Message.Message, event)) {
146
220
  this._processMessage(event);
147
- } else if (Obj.instanceOf(AgentStatus, event)) {
221
+ } else if (Obj2.instanceOf(AgentStatus, event)) {
148
222
  this._processAgentStatus(event);
149
223
  }
150
224
  }
@@ -246,11 +320,17 @@ var ExecutionGraph = class {
246
320
  */
247
321
  _updatePendingToolResults(toolCallId, agentStatusId) {
248
322
  const toolResultId = this._pendingToolResults.get(toolCallId);
249
- if (!toolResultId) return;
323
+ if (!toolResultId) {
324
+ return;
325
+ }
250
326
  const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
251
- if (!toolResultCommit) return;
327
+ if (!toolResultCommit) {
328
+ return;
329
+ }
252
330
  const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
253
- if (!toolCallCommitId) return;
331
+ if (!toolCallCommitId) {
332
+ return;
333
+ }
254
334
  const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
255
335
  if (toolCallIndex !== -1) {
256
336
  toolResultCommit.parents[toolCallIndex] = agentStatusId;
@@ -262,7 +342,9 @@ var ExecutionGraph = class {
262
342
  */
263
343
  _handleLateToolResultUpdate(toolCallId, toolResultId) {
264
344
  const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
265
- if (!toolCallCommitId) return;
345
+ if (!toolCallCommitId) {
346
+ return;
347
+ }
266
348
  const messageId = toolCallCommitId.split("_toolCall_")[0];
267
349
  const toolCallBranch = `${messageId}_${toolCallId}`;
268
350
  const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
@@ -365,7 +447,9 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
365
447
  const timestamp = new Date(message.created);
366
448
  switch (block._tag) {
367
449
  case "text":
368
- if (!block.text.trim().length) return null;
450
+ if (!block.text.trim().length) {
451
+ return null;
452
+ }
369
453
  return {
370
454
  id: getGenericBlockId(message.id, idx),
371
455
  branch,
@@ -378,7 +462,7 @@ var createBlockCommit = (block, message, branch, parents, idx) => {
378
462
  ],
379
463
  message: "Processing request..."
380
464
  } : {
381
- icon: "ph--robot--regular",
465
+ icon: "ph--drone--regular",
382
466
  message: `Response (${block.text.split(" ").length} words)`
383
467
  }
384
468
  };
@@ -480,57 +564,1179 @@ var stringifyRef = (ref) => {
480
564
  return ref.dxn.asEchoDXN()?.echoId ?? ref.dxn.asQueueDXN()?.objectId ?? "";
481
565
  };
482
566
  var stringifyObject = (obj) => {
483
- return Obj.getLabel(obj) ?? Obj.getTypename(obj) ?? obj.id;
567
+ return Obj2.getLabel(obj) ?? Obj2.getTypename(obj) ?? obj.id;
568
+ };
569
+
570
+ // src/util/tracing.ts
571
+ import * as Schema3 from "effect/Schema";
572
+ import { Trace } from "@dxos/compute";
573
+ import { Obj as Obj3 } from "@dxos/echo";
574
+ import { ContentBlock as ContentBlock2, Actor } from "@dxos/types";
575
+ var PartialBlock = Trace.EventType("assistant.partialBlock", {
576
+ schema: Schema3.Struct({
577
+ messageId: Obj3.ID,
578
+ role: Actor.Role,
579
+ block: ContentBlock2.Any
580
+ }),
581
+ isEphemeral: true
582
+ });
583
+ var CompleteBlock = Trace.EventType("assistant.completeBlock", {
584
+ schema: Schema3.Struct({
585
+ messageId: Obj3.ID,
586
+ role: Actor.Role,
587
+ block: ContentBlock2.Any
588
+ }),
589
+ isEphemeral: false
590
+ });
591
+ var AgentRequestBegin = Trace.EventType("assistant.agentRequestBegin", {
592
+ schema: Schema3.Struct({}),
593
+ isEphemeral: false
594
+ });
595
+ var AgentRequestEnd = Trace.EventType("assistant.agentRequestEnd", {
596
+ schema: Schema3.Struct({}),
597
+ isEphemeral: false
598
+ });
599
+ var McpServerError = Trace.EventType("assistant.mcpServerError", {
600
+ schema: Schema3.Struct({
601
+ url: Schema3.String,
602
+ protocol: Schema3.Literal("sse", "http"),
603
+ message: Schema3.String
604
+ }),
605
+ isEphemeral: true
606
+ });
607
+
608
+ // src/functions/services.ts
609
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/compute/assistant/src/functions/services.ts";
610
+ var makeToolResolverFromOperations = ({ toolkit: extraToolkit = OpaqueToolkit.empty } = {}) => {
611
+ return Layer.effect(ToolResolverService, Effect2.gen(function* () {
612
+ const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
613
+ const operationRegistry = yield* OperationRegistry.Service;
614
+ return {
615
+ resolve: (id) => Effect2.gen(function* () {
616
+ const toolkit = OpaqueToolkit.merge(extraToolkit, toolkitProvider.getToolkit());
617
+ const tool = toolkit.toolkit.tools[id];
618
+ if (tool) {
619
+ return tool;
620
+ }
621
+ return yield* operationRegistry.resolve(id).pipe(Effect2.flatMap(Option.match({
622
+ onSome: (_) => Effect2.succeed(projectFunctionToTool(_)),
623
+ onNone: () => Effect2.fail(new AiToolNotFoundError(id))
624
+ })));
625
+ })
626
+ };
627
+ }));
628
+ };
629
+ var makeToolExecutionService = (opts) => Layer.effect(ToolExecutionService, Effect2.gen(function* () {
630
+ const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
631
+ const toolkit = toolkitProvider.getToolkit();
632
+ const toolkitHandler = yield* toolkit.toolkit.pipe(Effect2.provide(toolkit.layer));
633
+ invariant(isHandlerLike(toolkitHandler), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 42, S: this, A: ["isHandlerLike(toolkitHandler)", ""] });
634
+ return {
635
+ handlersFor: (toolkit2) => {
636
+ const makeHandler = (tool) => {
637
+ return Effect2.fn(`toolFunctionHandler ${tool.name}`)(function* (input) {
638
+ if (toolkitHandler.tools[tool.name]) {
639
+ if (Tool.isProviderDefined(tool)) {
640
+ throw new Error("Attempted to call a provider-defined tool");
641
+ }
642
+ const { result } = yield* toolkitHandler.handle(tool.name, input);
643
+ return result;
644
+ }
645
+ return yield* opts.invoke(tool, input).pipe(Effect2.catchAllDefect((defect) => Effect2.fail(defect)));
646
+ });
647
+ };
648
+ return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
649
+ }
650
+ };
651
+ }));
652
+ var makeToolExecutionServiceFromOperationInvoker = () => {
653
+ return Layer.unwrapEffect(Effect2.gen(function* () {
654
+ const operationInvoker = yield* Operation.Service;
655
+ return makeToolExecutionService({
656
+ invoke: (tool, input) => Effect2.gen(function* () {
657
+ const operationDef = getOperationFromTool(tool).pipe(Option.getOrThrow);
658
+ return yield* operationInvoker.invoke(operationDef, input).pipe(Effect2.orDie);
659
+ })
660
+ });
661
+ }));
662
+ };
663
+ var ToolExecutionServices = Layer.mergeAll(makeToolResolverFromOperations(), makeToolExecutionServiceFromOperationInvoker());
664
+ var FunctionToolAnnotation = class extends Context.Tag("@dxos/assistant/FunctionToolAnnotation")() {
665
+ };
666
+ var getOperationFromTool = (tool) => {
667
+ return Context.getOption(FunctionToolAnnotation)(tool.annotations).pipe(Option.map(({ definition }) => definition));
668
+ };
669
+ var toolCache = /* @__PURE__ */ new WeakMap();
670
+ var projectFunctionToTool = (fn2) => {
671
+ if (toolCache.has(fn2)) {
672
+ return toolCache.get(fn2);
673
+ }
674
+ const tool = Tool.make(makeToolName(fn2.meta.name ?? fn2.meta.key), {
675
+ description: fn2.meta.description,
676
+ parameters: createStructFieldsFromSchema(fn2.input),
677
+ failure: Schema4.Any
678
+ }).annotate(FunctionToolAnnotation, {
679
+ definition: fn2
680
+ });
681
+ toolCache.set(fn2, tool);
682
+ return tool;
683
+ };
684
+ var makeToolName = (name) => {
685
+ const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, "-");
686
+ invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 100, S: void 0, A: ["toolName.match(/^[a-z_][a-z0-9-_]*$/)", ""] });
687
+ return toolName;
688
+ };
689
+ var createStructFieldsFromSchema = (schema) => {
690
+ switch (schema.ast._tag) {
691
+ case "TypeLiteral":
692
+ return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
693
+ prop.name,
694
+ Schema4.make(mapSchemaTypeForLLM(prop.type))
695
+ ]));
696
+ case "VoidKeyword":
697
+ return {};
698
+ default:
699
+ return todo(`Unsupported schema AST: ${schema.ast._tag}`);
700
+ }
701
+ };
702
+ var mapSchemaTypeForLLM = (ast) => {
703
+ if (Ref2.isRefType(ast)) {
704
+ const description = ast.annotations.description ? ast.annotations.description + "\n" + RefFromLLM.ast.annotations.description : RefFromLLM.ast.annotations.description;
705
+ return RefFromLLM.annotations({
706
+ description
707
+ }).ast;
708
+ } else if (SchemaAST.isTupleType(ast)) {
709
+ return new SchemaAST.TupleType(ast.elements.map((t) => new SchemaAST.OptionalType(mapSchemaTypeForLLM(t.type), t.isOptional, t.annotations)), ast.rest.map((t) => new SchemaAST.Type(mapSchemaTypeForLLM(t.type), t.annotations)), ast.isReadonly, ast.annotations);
710
+ } else if (SchemaAST.isTypeLiteral(ast)) {
711
+ return new SchemaAST.TypeLiteral(ast.propertySignatures.map((p) => new SchemaAST.PropertySignature(p.name, mapSchemaTypeForLLM(p.type), p.isOptional, p.isReadonly, p.annotations)), ast.indexSignatures, ast.annotations);
712
+ }
713
+ return ast;
714
+ };
715
+ var isHandlerLike = (value) => {
716
+ return typeof value.tools === "object" && typeof value.handle === "function";
717
+ };
718
+
719
+ // src/request/format.ts
720
+ import * as Effect3 from "effect/Effect";
721
+ import * as Function from "effect/Function";
722
+ import * as Option2 from "effect/Option";
723
+ import { Template } from "@dxos/compute";
724
+ import { Obj as Obj4 } from "@dxos/echo";
725
+ import { ObjectVersion } from "@dxos/echo-db";
726
+ import { log as log2 } from "@dxos/log";
727
+ import { Message as Message2 } from "@dxos/types";
728
+ import { trim as trim2 } from "@dxos/util";
729
+
730
+ // src/request/artifact-diff.ts
731
+ import * as Context2 from "effect/Context";
732
+ var ArtifactDiffResolver = class extends Context2.Tag("@dxos/assistant/ArtifactDiffResolver")() {
733
+ };
734
+
735
+ // src/request/format.ts
736
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/compute/assistant/src/request/format.ts";
737
+ var formatSystemPrompt = ({ system, blueprints = [], objects = [] }) => Effect3.gen(function* () {
738
+ const blueprintDefs = yield* Function.pipe(blueprints, Effect3.forEach((blueprint) => Effect3.succeed(blueprint.instructions)), Effect3.flatMap(Effect3.forEach((template) => Effect3.gen(function* () {
739
+ return trim2`
740
+ <blueprint>
741
+ ${yield* Template.processTemplate(template)}
742
+ </blueprint>
743
+ `;
744
+ }))), Effect3.map((blueprints2) => blueprints2.length > 0 ? [
745
+ "## Blueprints Definitions",
746
+ ...blueprints2
747
+ ].join("\n\n") : void 0));
748
+ const objectDefs = yield* Function.pipe(objects, Effect3.forEach((object) => Effect3.succeed(trim2`
749
+ <object>
750
+ <dxn>${Obj4.getDXN(object)}</dxn>
751
+ <typename>${Obj4.getTypename(object)}</typename>
752
+ </object>
753
+ `)), Effect3.map((objects2) => objects2.length > 0 ? [
754
+ "## Context Objects",
755
+ ...objects2
756
+ ].join("\n\n") : void 0));
757
+ return yield* Function.pipe(Effect3.succeed([
758
+ system,
759
+ blueprintDefs,
760
+ objectDefs
761
+ ].filter((def) => def !== void 0)), Effect3.map((parts) => parts.join("\n\n")));
762
+ }).pipe(Effect3.withSpan("formatSystemPrompt"));
763
+ var formatUserPrompt = ({ prompt, history = [] }) => Effect3.gen(function* () {
764
+ const blocks = [];
765
+ const artifactDiffResolver = yield* Effect3.serviceOption(ArtifactDiffResolver);
766
+ if (Option2.isSome(artifactDiffResolver)) {
767
+ const versions = gatherObjectVersions(history);
768
+ const artifactDiff = yield* Effect3.tryPromise({
769
+ try: () => artifactDiffResolver.value.resolve([
770
+ ...versions.entries()
771
+ ].map(([id, version]) => ({
772
+ id,
773
+ lastVersion: version
774
+ }))),
775
+ catch: AiAssistantError.wrap({
776
+ message: "Artifact diff resolution error"
777
+ })
778
+ });
779
+ log2("version", {
780
+ artifactDiff,
781
+ versions
782
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 65, S: this });
783
+ for (const [id, { version }] of [
784
+ ...artifactDiff.entries()
785
+ ]) {
786
+ if (ObjectVersion.equals(version, versions.get(id))) {
787
+ artifactDiff.delete(id);
788
+ continue;
789
+ }
790
+ blocks.push({
791
+ _tag: "anchor",
792
+ objectId: id,
793
+ version
794
+ });
795
+ }
796
+ if (artifactDiff.size > 0) {
797
+ blocks.push(createArtifactUpdateBlock(artifactDiff));
798
+ }
799
+ }
800
+ return Obj4.make(Message2.Message, {
801
+ created: (/* @__PURE__ */ new Date()).toISOString(),
802
+ sender: {
803
+ role: "user"
804
+ },
805
+ blocks: typeof prompt === "string" ? [
806
+ ...blocks,
807
+ {
808
+ _tag: "text",
809
+ text: prompt
810
+ }
811
+ ] : [
812
+ ...blocks,
813
+ ...prompt
814
+ ]
815
+ });
816
+ }).pipe(Effect3.withSpan("formatUserPrompt"));
817
+ var gatherObjectVersions = (messages) => {
818
+ const artifactIds = /* @__PURE__ */ new Map();
819
+ for (const message of messages) {
820
+ for (const block of message.blocks) {
821
+ if (block._tag === "anchor") {
822
+ artifactIds.set(block.objectId, block.version);
823
+ }
824
+ }
825
+ }
826
+ return artifactIds;
827
+ };
828
+ var createArtifactUpdateBlock = (artifactDiff) => {
829
+ return {
830
+ _tag: "text",
831
+ // TODO(dmaretskyi): Does this need to be a special content-block?
832
+ disposition: "synthetic",
833
+ text: trim2`
834
+ The following artifacts have been updated since the last message:
835
+ ${[
836
+ ...artifactDiff.entries()
837
+ ].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
838
+ ${diff}` : ""}</changed-artifact>`).join("\n")}
839
+ `
840
+ };
841
+ };
842
+
843
+ // src/request/observer.ts
844
+ import * as Effect4 from "effect/Effect";
845
+ import * as Function2 from "effect/Function";
846
+ var GenerationObserver = Object.freeze({
847
+ make: ({ onBegin = Function2.constant(Effect4.void), onPart = Function2.constant(Effect4.void), onBlock = Function2.constant(Effect4.void), onEnd = Function2.constant(Effect4.void), onMessage = Function2.constant(Effect4.void) } = {}) => ({
848
+ onBegin,
849
+ onPart,
850
+ onBlock,
851
+ onEnd,
852
+ onMessage
853
+ }),
854
+ noop: () => GenerationObserver.make(),
855
+ /**
856
+ * Debug printer to be used in unit-tests and browser devtools.
857
+ */
858
+ fromPrinter: (printer) => GenerationObserver.make({
859
+ onBlock: (block) => Effect4.sync(() => {
860
+ if (block.pending) {
861
+ return;
862
+ }
863
+ printer.printContentBlock(block);
864
+ }),
865
+ onMessage: (message) => Effect4.sync(() => {
866
+ if (message.sender.role === "assistant") {
867
+ return;
868
+ }
869
+ printer.printMessage(message);
870
+ })
871
+ })
872
+ });
873
+
874
+ // src/request/AiRequest.ts
875
+ var AiRequest_exports = {};
876
+ __export(AiRequest_exports, {
877
+ Request: () => Request
878
+ });
879
+ import * as LanguageModel from "@effect/ai/LanguageModel";
880
+ import * as Array2 from "effect/Array";
881
+ import * as Chunk from "effect/Chunk";
882
+ import * as Effect5 from "effect/Effect";
883
+ import { pipe as pipe2 } from "effect/Function";
884
+ import * as Option3 from "effect/Option";
885
+ import * as Stream from "effect/Stream";
886
+ import { AiParser, AiPreprocessor, AiSummarizer, callTool, withoutToolCallParising } from "@dxos/ai";
887
+ import { Trace as Trace2 } from "@dxos/compute";
888
+ import { Obj as Obj5 } from "@dxos/echo";
889
+ import { log as log3 } from "@dxos/log";
890
+ import { ContentBlock as ContentBlock3, Message as Message3 } from "@dxos/types";
891
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/compute/assistant/src/request/AiRequest.ts";
892
+ var Request = class {
893
+ _options;
894
+ /** Prevents concurrent execution of session. */
895
+ _semaphore = Effect5.runSync(Effect5.makeSemaphore(1));
896
+ _observer;
897
+ _onOutput;
898
+ /** Message history from queue. */
899
+ // TODO(burdon): Evolve into supporting a git-like graph of messages.
900
+ _history = [];
901
+ /** Pending messages for this session (incl. the current prompt). */
902
+ _pending = [];
903
+ _started = 0;
904
+ _ended = 0;
905
+ _toolCalls = 0;
906
+ constructor(_options = {}) {
907
+ this._options = _options;
908
+ this._observer = _options.observer ?? GenerationObserver.noop();
909
+ this._onOutput = _options.onOutput ?? (() => Effect5.void);
910
+ }
911
+ get duration() {
912
+ return this._ended - this._started;
913
+ }
914
+ get toolCalls() {
915
+ return this._toolCalls;
916
+ }
917
+ get pending() {
918
+ return this._pending;
919
+ }
920
+ _submitMessage = (message) => Effect5.gen(this, function* () {
921
+ this._pending.push(message);
922
+ yield* this._observer.onMessage(message);
923
+ for (const block of message.blocks) {
924
+ log3("write complete block", {
925
+ messageId: message.id,
926
+ role: message.sender.role,
927
+ block: JSON.stringify(block)
928
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 58, S: this });
929
+ yield* Trace2.write(CompleteBlock, {
930
+ messageId: message.id,
931
+ role: message.sender.role,
932
+ block
933
+ });
934
+ }
935
+ yield* this._onOutput(message);
936
+ return message;
937
+ });
938
+ getToolCalls = () => pipe2([
939
+ ...this._history,
940
+ ...this._pending
941
+ ], Array2.reverse, Array2.takeWhile((_) => _.sender.role === "assistant"), Array2.flatMap((_) => _.blocks.filter(ContentBlock3.is("toolCall")).map((block) => ({
942
+ block,
943
+ message: _
944
+ }))), Array2.filter((_) => !_.block.providerExecuted), Array2.reverse);
945
+ /**
946
+ * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
947
+ * Must be called before `runTurn()`.
948
+ */
949
+ begin = ({ prompt, system, history = [], blueprints = [], objects = [] }) => Effect5.gen(this, function* () {
950
+ this._started = Date.now();
951
+ this._history = [
952
+ ...history
953
+ ];
954
+ this._pending = [];
955
+ const systemPrompt = yield* formatSystemPrompt({
956
+ system,
957
+ blueprints,
958
+ objects
959
+ }).pipe(Effect5.orDie);
960
+ if (this._options.summarizationThreshold !== void 0) {
961
+ const tokenCount = yield* AiPreprocessor.estimateTokens(yield* AiPreprocessor.preprocessPrompt([
962
+ ...this._history
963
+ ], {
964
+ system: systemPrompt
965
+ }));
966
+ if (tokenCount > this._options.summarizationThreshold) {
967
+ const summary = yield* AiSummarizer.summarize([
968
+ ...this._history
969
+ ]);
970
+ yield* this._submitMessage(summary);
971
+ }
972
+ }
973
+ yield* this._submitMessage(yield* formatUserPrompt({
974
+ prompt,
975
+ history
976
+ }));
977
+ }).pipe(Effect5.withSpan("AiRequest.begin"));
978
+ /**
979
+ * Execute a single turn: one LLM generation followed by tool execution.
980
+ * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled blueprints).
981
+ */
982
+ runAgentTurn = ({ system, toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
983
+ log3.info("request", {
984
+ system: {
985
+ snippet: createSnippet(system),
986
+ length: system.length
987
+ },
988
+ pending: this._pending.length,
989
+ history: this._history.length
990
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 115, S: this });
991
+ const prompt = yield* AiPreprocessor.preprocessPrompt([
992
+ ...this._history,
993
+ ...this._pending
994
+ ], {
995
+ system,
996
+ cacheControl: "ephemeral"
997
+ });
998
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
999
+ const observer = this._observer;
1000
+ let currentMessageId = null;
1001
+ const messages = yield* LanguageModel.streamText({
1002
+ prompt,
1003
+ toolkit,
1004
+ disableToolCallResolution: true
1005
+ }).pipe(withoutToolCallParising, AiParser.parseResponse({
1006
+ emitPartial: true,
1007
+ onBegin: () => observer.onBegin(),
1008
+ onBlock: (block) => observer.onBlock(block),
1009
+ onPart: (part) => observer.onPart(part),
1010
+ onEnd: (summary) => observer.onEnd(summary)
1011
+ }), Stream.mapEffect((block) => Effect5.gen(this, function* () {
1012
+ if (block.pending) {
1013
+ currentMessageId ??= Obj5.ID.random();
1014
+ log3("emit ephemeral message", {
1015
+ id: currentMessageId,
1016
+ type: block._tag
1017
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 146, S: this });
1018
+ yield* Trace2.write(PartialBlock, {
1019
+ messageId: currentMessageId,
1020
+ role: "assistant",
1021
+ block
1022
+ });
1023
+ return Option3.none();
1024
+ } else {
1025
+ currentMessageId ??= Obj5.ID.random();
1026
+ const id = currentMessageId;
1027
+ currentMessageId = null;
1028
+ log3("emit complete message", {
1029
+ id,
1030
+ type: block._tag
1031
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 160, S: this });
1032
+ const message = Obj5.make(Message3.Message, {
1033
+ id,
1034
+ created: (/* @__PURE__ */ new Date()).toISOString(),
1035
+ sender: {
1036
+ role: "assistant"
1037
+ },
1038
+ blocks: [
1039
+ block
1040
+ ]
1041
+ });
1042
+ return Option3.some(yield* this._submitMessage(message));
1043
+ }
1044
+ }), {
1045
+ concurrency: 1,
1046
+ unordered: false
1047
+ }), Stream.filterMap((_) => _), Stream.runCollect, Effect5.map(Chunk.toArray));
1048
+ log3.info("messages", {
1049
+ messages
1050
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 180, S: this });
1051
+ const toolCalls = this.getToolCalls();
1052
+ if (toolCalls.length === 0) {
1053
+ this._ended = Date.now();
1054
+ return {
1055
+ messages,
1056
+ done: true
1057
+ };
1058
+ } else if (!toolkit) {
1059
+ throw new Error("No toolkit provided");
1060
+ }
1061
+ return {
1062
+ messages,
1063
+ done: false
1064
+ };
1065
+ }).pipe(Effect5.withSpan("AiRequest.runAgentTurn"));
1066
+ runTools = ({ toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
1067
+ const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
1068
+ const toolCalls = this.getToolCalls();
1069
+ const toolResults = yield* Effect5.forEach(toolCalls, ({ block, message }) => {
1070
+ if (!toolkit) {
1071
+ throw new Error("No toolkit provided");
1072
+ }
1073
+ return callTool(toolkit, block);
1074
+ });
1075
+ yield* this._submitMessage(Obj5.make(Message3.Message, {
1076
+ created: (/* @__PURE__ */ new Date()).toISOString(),
1077
+ sender: {
1078
+ role: "tool"
1079
+ },
1080
+ blocks: toolResults
1081
+ }));
1082
+ this._toolCalls += toolResults.length;
1083
+ }).pipe(Effect5.withSpan("AiRequest.runTools"));
1084
+ /**
1085
+ * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
1086
+ */
1087
+ run = ({ prompt, system: systemTemplate, history = [], objects = [], blueprints = [], toolkit }) => Effect5.gen(this, function* () {
1088
+ yield* this.begin({
1089
+ prompt,
1090
+ system: systemTemplate,
1091
+ history,
1092
+ objects,
1093
+ blueprints
1094
+ });
1095
+ const system = yield* formatSystemPrompt({
1096
+ system: systemTemplate,
1097
+ blueprints,
1098
+ objects
1099
+ }).pipe(Effect5.orDie);
1100
+ do {
1101
+ const { done } = yield* this.runAgentTurn({
1102
+ system,
1103
+ toolkit
1104
+ });
1105
+ if (done) {
1106
+ break;
1107
+ }
1108
+ yield* this.runTools({
1109
+ toolkit
1110
+ });
1111
+ } while (true);
1112
+ log3("done", {
1113
+ pending: this._pending.length,
1114
+ duration: this.duration,
1115
+ tools: this._toolCalls
1116
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 243, S: this });
1117
+ return this._pending;
1118
+ }).pipe(this._semaphore.withPermits(1), Effect5.withSpan("AiRequest.run"));
1119
+ };
1120
+ var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
1121
+ text.slice(0, len),
1122
+ "...",
1123
+ text.slice(-len)
1124
+ ].join("");
1125
+
1126
+ // src/session/toolkit.ts
1127
+ import * as Toolkit from "@effect/ai/Toolkit";
1128
+ import * as Effect6 from "effect/Effect";
1129
+ import * as Layer2 from "effect/Layer";
1130
+ import { OpaqueToolkit as OpaqueToolkit2, ToolExecutionService as ToolExecutionService2, ToolResolverService as ToolResolverService2 } from "@dxos/ai";
1131
+ import { isTruthy } from "@dxos/util";
1132
+ var createToolkit = ({ toolkit: toolkitProp, blueprints = [], opaqueToolkits = [] }) => Effect6.gen(function* () {
1133
+ const blueprintToolkit = yield* ToolResolverService2.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
1134
+ const blueprintToolHandler = yield* blueprintToolkit.toContext(ToolExecutionService2.handlersFor(blueprintToolkit));
1135
+ const opaqueToolkit = OpaqueToolkit2.merge(...opaqueToolkits);
1136
+ const toolkitDefs = [
1137
+ toolkitProp?.toolkit,
1138
+ blueprintToolkit,
1139
+ opaqueToolkit.toolkit
1140
+ ].filter(isTruthy);
1141
+ const mergedToolkit = Toolkit.merge(...toolkitDefs);
1142
+ const combinedHandlerLayer = Layer2.mergeAll(Layer2.succeedContext(blueprintToolHandler), toolkitProp?.layer ?? OpaqueToolkit2.empty.layer, opaqueToolkit.layer);
1143
+ return OpaqueToolkit2.make(mergedToolkit, combinedHandlerLayer);
1144
+ });
1145
+
1146
+ // src/session/AiContext.ts
1147
+ var AiContext_exports = {};
1148
+ __export(AiContext_exports, {
1149
+ Binder: () => Binder,
1150
+ Binding: () => Binding,
1151
+ Bindings: () => Bindings,
1152
+ Service: () => Service
1153
+ });
1154
+ import { Atom, Registry } from "@effect-atom/atom-react";
1155
+ import * as EArray from "effect/Array";
1156
+ import * as Context3 from "effect/Context";
1157
+ import * as Effect7 from "effect/Effect";
1158
+ import * as Function3 from "effect/Function";
1159
+ import * as Runtime from "effect/Runtime";
1160
+ import * as Schema5 from "effect/Schema";
1161
+ import { Blueprint } from "@dxos/compute";
1162
+ import { Resource } from "@dxos/context";
1163
+ import { DXN as DXN2, Feed, Obj as Obj6, Query, Ref as Ref3, Type as Type2 } from "@dxos/echo";
1164
+ import { assertArgument } from "@dxos/invariant";
1165
+ import { log as log4 } from "@dxos/log";
1166
+ import { ComplexSet, isNonNullable as isNonNullable3 } from "@dxos/util";
1167
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/AiContext.ts";
1168
+ var Binding = Schema5.Struct({
1169
+ blueprints: Schema5.Struct({
1170
+ added: Schema5.Array(Ref3.Ref(Blueprint.Blueprint)),
1171
+ removed: Schema5.Array(Ref3.Ref(Blueprint.Blueprint))
1172
+ }),
1173
+ objects: Schema5.Struct({
1174
+ added: Schema5.Array(Ref3.Ref(Obj6.Unknown)),
1175
+ removed: Schema5.Array(Ref3.Ref(Obj6.Unknown))
1176
+ })
1177
+ }).pipe(Type2.object({
1178
+ typename: "org.dxos.type.contextBinding",
1179
+ version: "0.1.0"
1180
+ }));
1181
+ var Bindings = class {
1182
+ blueprints = new ComplexSet((ref) => ref.dxn.toString());
1183
+ // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
1184
+ objects = new ComplexSet((ref) => ref.dxn.asEchoDXN()?.echoId);
1185
+ toJSON() {
1186
+ return {
1187
+ blueprints: EArray.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),
1188
+ objects: EArray.fromIterable(this.objects).map((ref) => ref.dxn.toString())
1189
+ };
1190
+ }
1191
+ };
1192
+ var Binder = class extends Resource {
1193
+ _blueprints = Atom.make([]).pipe(Atom.keepAlive);
1194
+ _objects = Atom.make([]).pipe(Atom.keepAlive);
1195
+ _registry;
1196
+ _feed;
1197
+ _runtime;
1198
+ #bindingsQuery;
1199
+ constructor(options) {
1200
+ super();
1201
+ assertArgument(options.feed, "options.feed", "Feed is required");
1202
+ assertArgument(options.runtime, "options.runtime", "Feed runtime is required");
1203
+ this._feed = options.feed;
1204
+ this._runtime = options.runtime;
1205
+ this._registry = options.registry ?? Registry.make();
1206
+ }
1207
+ /**
1208
+ * Returns the blueprints atom for subscription.
1209
+ */
1210
+ get blueprints() {
1211
+ return this._blueprints;
1212
+ }
1213
+ /**
1214
+ * Returns the objects atom for subscription.
1215
+ */
1216
+ get objects() {
1217
+ return this._objects;
1218
+ }
1219
+ /**
1220
+ * Gets the current blueprints value.
1221
+ */
1222
+ getBlueprints() {
1223
+ return this._registry.get(this._blueprints);
1224
+ }
1225
+ /**
1226
+ * Gets the current objects value.
1227
+ */
1228
+ getObjects() {
1229
+ return this._registry.get(this._objects);
1230
+ }
1231
+ /**
1232
+ * Subscribe to changes in blueprints.
1233
+ */
1234
+ subscribeBlueprints(cb) {
1235
+ return this._registry.subscribe(this._blueprints, () => cb(this._registry.get(this._blueprints)));
1236
+ }
1237
+ /**
1238
+ * Subscribe to changes in objects.
1239
+ */
1240
+ subscribeObjects(cb) {
1241
+ return this._registry.subscribe(this._objects, () => cb(this._registry.get(this._objects)));
1242
+ }
1243
+ async _open() {
1244
+ this.#bindingsQuery = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Query.type(Binding)));
1245
+ const initialResults = await this.#bindingsQuery.run();
1246
+ await this._updateBindings(initialResults);
1247
+ this._ctx.onDispose(this.#bindingsQuery.subscribe(async () => {
1248
+ await this._updateBindings(this.#bindingsQuery.results);
1249
+ }));
1250
+ }
1251
+ /**
1252
+ * Re-reads bindings from the feed to pick up changes made by other processes.
1253
+ */
1254
+ async sync() {
1255
+ if (this.#bindingsQuery) {
1256
+ const results = await this.#bindingsQuery.run();
1257
+ log4("sync", {
1258
+ bindingItems: results.length
1259
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 107, S: this });
1260
+ await this._updateBindings(results);
1261
+ log4("sync complete", {
1262
+ blueprints: this._registry.get(this._blueprints).length,
1263
+ blueprintKeys: this._registry.get(this._blueprints).map((bp) => Blueprint.getKey(bp))
1264
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 111, S: this });
1265
+ }
1266
+ }
1267
+ async _updateBindings(items) {
1268
+ if (items.length === 0) {
1269
+ return;
1270
+ }
1271
+ const bindings = this._reduce(items);
1272
+ log4("_updateBindings", {
1273
+ items: items.length,
1274
+ blueprintRefs: [
1275
+ ...bindings.blueprints
1276
+ ].map((ref) => ({
1277
+ dxn: ref.dxn.toString(),
1278
+ available: ref.isAvailable
1279
+ }))
1280
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 123, S: this });
1281
+ const currentBlueprints = this._registry.get(this._blueprints);
1282
+ const currentObjects = this._registry.get(this._objects);
1283
+ const resolvedBlueprints = await this._resolve(bindings.blueprints, currentBlueprints);
1284
+ const resolvedObjects = await this._resolve(bindings.objects, currentObjects);
1285
+ log4("_updateBindings resolved", {
1286
+ resolvedBlueprints: resolvedBlueprints.length,
1287
+ resolvedBlueprintKeys: resolvedBlueprints.map((bp) => Blueprint.getKey(bp))
1288
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 137, S: this });
1289
+ const reducedBlueprintDxns = new ComplexSet(DXN2.hash, [
1290
+ ...bindings.blueprints
1291
+ ].map((ref) => ref.dxn));
1292
+ const reducedObjectDxns = new ComplexSet(DXN2.hash, [
1293
+ ...bindings.objects
1294
+ ].map((ref) => ref.dxn));
1295
+ const filteredBlueprints = currentBlueprints.filter((obj) => reducedBlueprintDxns.has(Obj6.getDXN(obj)));
1296
+ const filteredObjects = currentObjects.filter((obj) => reducedObjectDxns.has(Obj6.getDXN(obj)));
1297
+ const mergedBlueprints = this._mergeInto(filteredBlueprints, resolvedBlueprints);
1298
+ const mergedObjects = this._mergeInto(filteredObjects, resolvedObjects);
1299
+ this._registry.set(this._blueprints, mergedBlueprints);
1300
+ this._registry.set(this._objects, mergedObjects);
1301
+ log4("updated bindings", {
1302
+ blueprints: mergedBlueprints.length,
1303
+ objects: mergedObjects.length
1304
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 155, S: this });
1305
+ }
1306
+ async _close() {
1307
+ this._registry.set(this._blueprints, []);
1308
+ this._registry.set(this._objects, []);
1309
+ }
1310
+ async bind({ blueprints, objects }) {
1311
+ const currentBlueprints = this._registry.get(this._blueprints);
1312
+ const currentObjects = this._registry.get(this._objects);
1313
+ const { added: addedBlueprints, next: nextBlueprints } = this._processBindings(blueprints, currentBlueprints);
1314
+ const { added: addedObjects, next: nextObjects } = this._processBindings(objects, currentObjects);
1315
+ if (!addedBlueprints.length && !addedObjects.length) {
1316
+ return;
1317
+ }
1318
+ this._registry.set(this._blueprints, nextBlueprints);
1319
+ this._registry.set(this._objects, nextObjects);
1320
+ log4("bind", {
1321
+ blueprints: addedBlueprints.length,
1322
+ objects: addedObjects.length
1323
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 176, S: this });
1324
+ await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
1325
+ Obj6.make(Binding, {
1326
+ blueprints: {
1327
+ added: addedBlueprints,
1328
+ removed: []
1329
+ },
1330
+ objects: {
1331
+ added: addedObjects,
1332
+ removed: []
1333
+ }
1334
+ })
1335
+ ]));
1336
+ }
1337
+ async unbind({ blueprints, objects }) {
1338
+ if (!blueprints?.length && !objects?.length) {
1339
+ return;
1340
+ }
1341
+ const removedBlueprintDxns = (blueprints ?? []).map((ref) => ref.dxn);
1342
+ const removedObjectDxns = (objects ?? []).map((ref) => ref.dxn);
1343
+ if (removedBlueprintDxns.length > 0) {
1344
+ const current = this._registry.get(this._blueprints);
1345
+ this._registry.set(this._blueprints, current.filter((obj) => !removedBlueprintDxns.some((dxn) => DXN2.equalsEchoId(Obj6.getDXN(obj), dxn))));
1346
+ }
1347
+ if (removedObjectDxns.length > 0) {
1348
+ const current = this._registry.get(this._objects);
1349
+ this._registry.set(this._objects, current.filter((obj) => !removedObjectDxns.some((dxn) => DXN2.equalsEchoId(Obj6.getDXN(obj), dxn))));
1350
+ }
1351
+ log4("unbind", {
1352
+ blueprints: blueprints?.length,
1353
+ objects: objects?.length
1354
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 208, S: this });
1355
+ await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
1356
+ Obj6.make(Binding, {
1357
+ blueprints: {
1358
+ added: [],
1359
+ removed: blueprints ?? []
1360
+ },
1361
+ objects: {
1362
+ added: [],
1363
+ removed: objects ?? []
1364
+ }
1365
+ })
1366
+ ]));
1367
+ }
1368
+ /**
1369
+ * Process bindings to filter duplicates and determine next state.
1370
+ */
1371
+ _processBindings(refs, current) {
1372
+ const next = [
1373
+ ...current
1374
+ ];
1375
+ const added = [];
1376
+ if (!refs?.length) {
1377
+ return {
1378
+ added,
1379
+ next
1380
+ };
1381
+ }
1382
+ const seen = new Set(current.map((obj) => Obj6.getDXN(obj).toString()));
1383
+ for (const ref of refs) {
1384
+ const dxn = ref.dxn.toString();
1385
+ if (!seen.has(dxn)) {
1386
+ seen.add(dxn);
1387
+ added.push(ref);
1388
+ if (ref.isAvailable) {
1389
+ const target = ref.target;
1390
+ if (target) {
1391
+ next.push(target);
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+ return {
1397
+ added,
1398
+ next
1399
+ };
1400
+ }
1401
+ /**
1402
+ * Reduce results into sets of blueprints and objects.
1403
+ */
1404
+ _reduce(items) {
1405
+ return Function3.pipe(items, EArray.reduce(new Bindings(), (context, { blueprints, objects }) => {
1406
+ blueprints.added.forEach((ref) => context.blueprints.add(ref));
1407
+ blueprints.removed.forEach((ref) => context.blueprints.delete(ref));
1408
+ objects.added.forEach((ref) => context.objects.add(ref));
1409
+ objects.removed.forEach((ref) => {
1410
+ for (const obj of context.objects) {
1411
+ if (DXN2.equalsEchoId(obj.dxn, ref.dxn)) {
1412
+ context.objects.delete(obj);
1413
+ }
1414
+ }
1415
+ });
1416
+ return context;
1417
+ }));
1418
+ }
1419
+ /**
1420
+ * Merge resolved items into the current set, adding only items not already present (by DXN).
1421
+ */
1422
+ _mergeInto(current, resolved) {
1423
+ const seen = new Set(current.map((obj) => Obj6.getDXN(obj).toString()));
1424
+ const merged = [
1425
+ ...current
1426
+ ];
1427
+ for (const obj of resolved) {
1428
+ const dxn = Obj6.getDXN(obj).toString();
1429
+ if (!seen.has(dxn)) {
1430
+ seen.add(dxn);
1431
+ merged.push(obj);
1432
+ }
1433
+ }
1434
+ return merged;
1435
+ }
1436
+ /**
1437
+ * Resolve references to objects, loading them first if needed and falling back to existing objects.
1438
+ */
1439
+ async _resolve(refs, current) {
1440
+ const refArray = [
1441
+ ...refs
1442
+ ];
1443
+ await Promise.all(refArray.map((ref) => ref.tryLoad()));
1444
+ return refArray.map((ref) => {
1445
+ let target;
1446
+ if (ref.isAvailable) {
1447
+ target = ref.target;
1448
+ }
1449
+ return target ?? current.find((obj) => Obj6.getDXN(obj).toString() === ref.dxn.toString());
1450
+ }).filter(isNonNullable3);
1451
+ }
1452
+ };
1453
+ var Service = class _Service extends Context3.Tag("@dxos/assistant/AiContextService")() {
1454
+ static bindContext = ({ blueprints, objects }) => Effect7.gen(function* () {
1455
+ const { binder } = yield* _Service;
1456
+ yield* Effect7.promise(() => binder.bind({
1457
+ blueprints,
1458
+ objects
1459
+ }));
1460
+ });
1461
+ static findObjects = (type) => {
1462
+ return Effect7.gen(function* () {
1463
+ const { binder } = yield* _Service;
1464
+ return binder.getObjects().filter(Obj6.instanceOf(type));
1465
+ });
1466
+ };
1467
+ };
1468
+
1469
+ // src/session/AiSession.ts
1470
+ var AiSession_exports = {};
1471
+ __export(AiSession_exports, {
1472
+ Service: () => Service2,
1473
+ Session: () => Session
1474
+ });
1475
+ import * as Array4 from "effect/Array";
1476
+ import * as Context4 from "effect/Context";
1477
+ import * as Effect8 from "effect/Effect";
1478
+ import * as Either from "effect/Either";
1479
+ import { pipe as pipe4 } from "effect/Function";
1480
+ import * as Layer3 from "effect/Layer";
1481
+ import * as Record2 from "effect/Record";
1482
+ import * as Runtime2 from "effect/Runtime";
1483
+ import { Operation as Operation2, Trace as Trace3 } from "@dxos/compute";
1484
+ import { Resource as Resource2 } from "@dxos/context";
1485
+ import { Database as Database2, Feed as Feed2, Filter, Obj as Obj7 } from "@dxos/echo";
1486
+ import { acquireReleaseResource } from "@dxos/effect";
1487
+ import { invariant as invariant2 } from "@dxos/invariant";
1488
+ import { log as log5 } from "@dxos/log";
1489
+ import { McpToolkit } from "@dxos/mcp-client";
1490
+ import { Message as Message4 } from "@dxos/types";
1491
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/AiSession.ts";
1492
+ var SUMMARY_THRESHOLD = 8e4;
1493
+ var Session = class extends Resource2 {
1494
+ /**
1495
+ * Blueprints and objects bound to the session.
1496
+ */
1497
+ _binder;
1498
+ _feed;
1499
+ _runtime;
1500
+ constructor(options) {
1501
+ super();
1502
+ this._feed = options.feed;
1503
+ this._runtime = options.runtime;
1504
+ invariant2(this._feed, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 43, S: this, A: ["this._feed", ""] });
1505
+ invariant2(this._runtime, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 44, S: this, A: ["this._runtime", ""] });
1506
+ this._binder = new Binder({
1507
+ feed: this._feed,
1508
+ runtime: this._runtime,
1509
+ registry: options.registry
1510
+ });
1511
+ }
1512
+ async _open() {
1513
+ await this._binder.open(this._ctx);
1514
+ }
1515
+ get feed() {
1516
+ return this._feed;
1517
+ }
1518
+ get context() {
1519
+ return this._binder;
1520
+ }
1521
+ async getHistory() {
1522
+ const queryResult = await Runtime2.runPromise(this._runtime)(Feed2.query(this._feed, Filter.type(Message4.Message)));
1523
+ const items = await queryResult.run();
1524
+ return items.filter(Obj7.instanceOf(Message4.Message));
1525
+ }
1526
+ getTools() {
1527
+ return Effect8.gen(this, function* () {
1528
+ const toolkit = yield* createToolkit({
1529
+ blueprints: this.context.getBlueprints()
1530
+ });
1531
+ return toolkit.toolkit.tools;
1532
+ }).pipe(Effect8.orDie);
1533
+ }
1534
+ /**
1535
+ * Not provided by default, since users might want to override them.
1536
+ */
1537
+ makeToolExecutionServices() {
1538
+ return ToolExecutionServices.pipe(Layer3.provide(Operation2.withInvocationOptions({
1539
+ conversation: Obj7.getDXN(this._feed).toString()
1540
+ })));
1541
+ }
1542
+ /**
1543
+ * Creates a new cancelable request effect.
1544
+ */
1545
+ createRequest(params) {
1546
+ return Effect8.gen(this, function* () {
1547
+ const history = yield* Effect8.promise(() => this.getHistory());
1548
+ const blueprints = this.context.getBlueprints();
1549
+ const objects = this.context.getObjects();
1550
+ log5("run", {
1551
+ history: history.length,
1552
+ blueprints: blueprints.length,
1553
+ objects: objects.length
1554
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 87, S: this });
1555
+ const request = new AiRequest_exports.Request({
1556
+ summarizationThreshold: SUMMARY_THRESHOLD,
1557
+ observer: params.observer,
1558
+ onOutput: (message) => Effect8.promise(() => Runtime2.runPromise(this._runtime)(Feed2.append(this._feed, [
1559
+ message
1560
+ ])))
1561
+ });
1562
+ yield* request.begin({
1563
+ history,
1564
+ blueprints,
1565
+ objects,
1566
+ prompt: params.prompt,
1567
+ system: params.system
1568
+ });
1569
+ do {
1570
+ yield* Effect8.promise(() => this.context.sync());
1571
+ const currentBlueprints = this.context.getBlueprints();
1572
+ const mcps = yield* connectMcpServers(currentBlueprints, params.mcpServers);
1573
+ const toolkit = yield* createToolkit({
1574
+ toolkit: params.toolkit,
1575
+ blueprints: currentBlueprints,
1576
+ opaqueToolkits: mcps
1577
+ });
1578
+ log5("toolkit", {
1579
+ tools: Record2.keys(toolkit.toolkit.tools)
1580
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 116, S: this });
1581
+ const system = yield* formatSystemPrompt({
1582
+ system: params.system,
1583
+ blueprints: currentBlueprints,
1584
+ objects: this.context.getObjects()
1585
+ }).pipe(Effect8.orDie);
1586
+ const { done } = yield* request.runAgentTurn({
1587
+ system,
1588
+ toolkit
1589
+ });
1590
+ if (done) {
1591
+ break;
1592
+ }
1593
+ yield* request.runTools({
1594
+ toolkit
1595
+ });
1596
+ } while (true);
1597
+ log5("result", {
1598
+ messages: request.pending.length,
1599
+ duration: request.duration,
1600
+ toolCalls: request.toolCalls
1601
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 135, S: this });
1602
+ return [
1603
+ ...request.pending
1604
+ ];
1605
+ }).pipe(Effect8.provide(Layer3.mergeAll(Layer3.succeed(Service, {
1606
+ binder: this.context
1607
+ }), Layer3.succeed(Service2, this), Operation2.withInvocationOptions({
1608
+ conversation: Obj7.getDXN(this._feed).toString()
1609
+ }))), Effect8.withSpan("AiSession.createRequest"));
1610
+ }
1611
+ };
1612
+ var Service2 = class _Service extends Context4.Tag("@dxos/assistant/AiSessionService")() {
1613
+ /**
1614
+ * Create a new session layer from options.
1615
+ */
1616
+ static layer = (options) => aiContextFromSession.pipe(Layer3.provideMerge(Layer3.scoped(_Service, Effect8.gen(function* () {
1617
+ const session = yield* acquireReleaseResource(() => new Session(options));
1618
+ return session;
1619
+ }))));
1620
+ /**
1621
+ * Create a new session with a new feed.
1622
+ */
1623
+ static layerNewFeed = (options) => Layer3.unwrapScoped(Effect8.gen(function* () {
1624
+ const feed = yield* Database2.add(Feed2.make());
1625
+ const runtime2 = yield* Effect8.runtime();
1626
+ return _Service.layer({
1627
+ ...options,
1628
+ feed,
1629
+ runtime: runtime2
1630
+ });
1631
+ }));
1632
+ /**
1633
+ * Run a prompt in the current session.
1634
+ */
1635
+ static run = (params) => Effect8.gen(function* () {
1636
+ const session = yield* _Service;
1637
+ return yield* session.createRequest(params);
1638
+ });
1639
+ };
1640
+ var aiContextFromSession = Layer3.effect(Service, Effect8.gen(function* () {
1641
+ const session = yield* Service2;
1642
+ return {
1643
+ binder: session.context
1644
+ };
1645
+ }));
1646
+ var connectMcpServers = (blueprints, spaceMcpServers = []) => {
1647
+ const blueprintServers = pipe4(blueprints, Array4.flatMap((_) => _.mcpServers ?? []), Array4.map(({ url, protocol, apiKey }) => ({
1648
+ url,
1649
+ protocol,
1650
+ apiKey
1651
+ })));
1652
+ const spaceServers = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
1653
+ url,
1654
+ protocol,
1655
+ apiKey
1656
+ }));
1657
+ const allServers = [
1658
+ ...blueprintServers,
1659
+ ...spaceServers
1660
+ ];
1661
+ return pipe4(allServers, Effect8.forEach((options) => McpToolkit.make(options).pipe(
1662
+ // NOTE: Type-inference fails here without explicit void return.
1663
+ Effect8.tap((toolkit) => log5.info("Connected to MCP server", {
1664
+ url: options.url,
1665
+ tools: Object.keys(toolkit.toolkit.tools).length
1666
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 199, S: void 0 })),
1667
+ // Surface typed connection failures via ephemeral trace + warn log, then drop the server.
1668
+ Effect8.tapError((error) => Effect8.gen(function* () {
1669
+ log5.warn("Failed to connect to MCP server", {
1670
+ url: error.url,
1671
+ protocol: error.protocol,
1672
+ message: error.message
1673
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 204, S: this });
1674
+ yield* Trace3.write(McpServerError, {
1675
+ url: error.url,
1676
+ protocol: error.protocol,
1677
+ message: error.message
1678
+ });
1679
+ })),
1680
+ // Catch unexpected defects too (e.g. malformed tool schemas) so a single broken
1681
+ // server can never abort the whole turn — surface them through the same channel.
1682
+ Effect8.catchAllDefect((defect) => Effect8.gen(function* () {
1683
+ const message = defect instanceof Error ? defect.message : String(defect);
1684
+ log5.warn("Unexpected MCP defect", {
1685
+ url: options.url,
1686
+ message
1687
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 218, S: this });
1688
+ yield* Trace3.write(McpServerError, {
1689
+ url: options.url,
1690
+ protocol: options.protocol,
1691
+ message: `Unexpected MCP failure: ${message}`
1692
+ });
1693
+ return yield* Effect8.fail(new McpToolkit.McpConnectionError({
1694
+ url: options.url,
1695
+ protocol: options.protocol,
1696
+ message
1697
+ }));
1698
+ })),
1699
+ Effect8.either
1700
+ )), Effect8.map(Array4.filterMap((_) => Either.getRight(_))));
484
1701
  };
485
1702
 
486
1703
  // src/templates/system.ts
487
1704
  import defaultsDeep from "lodash.defaultsdeep";
488
- import { Template } from "@dxos/blueprints";
1705
+ import { Template as Template2 } from "@dxos/compute";
489
1706
 
490
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/format.tpl?raw
1707
+ // raw-loader:/__w/dxos/dxos/packages/core/compute/assistant/src/templates/instructions/format.tpl?raw
491
1708
  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>\nDo not use bullets when listing suggestions.\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## Context\n\nThe current date and time is {{DATETIME}}.\n";
492
1709
 
493
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/instructions/system.tpl?raw
494
- 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## Navigation\n\n- When the user asks to open, go to, navigate to, or show a specific document, page, or object, use the navigation tools instead of loading content inline.\n- First, call the Resolve navigation targets tool to find the navigation path for the requested item.\n - Without arguments, it returns available pages that can be navigated to.\n - With a DXN in the query, it resolves that specific object to a navigation path.\n- If you know the object's DXN (e.g. from a database query or context objects), pass it in the query to get the exact navigation path.\n- Then, call the Open tool with the resolved navigation path(s) in the subject array to navigate the user to that item.\n- Do not respond with the document's content when the user asks to open it \u2014 open it in the main content area instead.\n- If multiple targets match, present the options to the user and let them choose which to open.\n\n## Context\n";
1710
+ // raw-loader:/__w/dxos/dxos/packages/core/compute/assistant/src/templates/instructions/system.tpl?raw
1711
+ 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## Navigation\n\n- When the user asks to open, go to, navigate to, or show a specific document, page, or object, use the navigation tools instead of loading content inline.\n- First, call the Resolve navigation targets tool to find the navigation path for the requested item.\n - Without arguments, it returns available pages that can be navigated to.\n - With a DXN in the query, it resolves that specific object to a navigation path.\n- If you know the object's DXN (e.g. from a database query or context objects), pass it in the query to get the exact navigation path.\n- Then, call the Open tool with the resolved navigation path(s) in the subject array to navigate the user to that item.\n- Do not respond with the document's content when the user asks to open it \u2014 open it in the main content area instead.\n- If multiple targets match, present the options to the user and let them choose which to open.\n\n## Response format\n\n- NEVER output narration text outside `<status>` tags or the final user-facing answer. Any progress update, transition sentence, or \"let me\u2026\" lead-in MUST be wrapped in `<status>...</status>`. Violating this is an error.\n- When updating the user about the progress of the work you are doing, put the update in a <status> XML tag.\n- Only when you need to show the result to the user or ask a question use a text block without status tags.\n- After a `</status>` tag, the next output must be either another `<status>` tag, a tool call, or the final user-facing answer \u2014 never a transition sentence.\n\n<example>\n// reasoning...\n<status>Looking for emails from Depot</status>\n// tool call..\n<status>Found 2 emails from Depot.</status>\n<status>Loading email details</status>\n// tool call\n<status>Located mailbox</status>\nI found **2 emails from Depot**:\n</example>\n\nDo not do (no status tags):\n\n<incorrect_example>\n// reasoning...\n// tool call..\nI found 2 emails from Depot. Let me load their details:\n// tool call\nI found **2 emails from Depot**:\n</incorrect_example>\n\nDo not do (transition sentence after a status tag, before tool calls):\n\n<incorrect_example>\n<status>Doing X</status>\nLet me start by doing X:\n// tool call\n</incorrect_example>\n\n- NEVER write a lead-in sentence before a tool call. Use a `<status>` tag instead.\n- Avoid using plain text to tell the user what you are about to do; instead, use status blocks.\n- WRONG: Let me get...\n- CORRECT: <status>Getting...</status>";
495
1712
 
496
1713
  // src/templates/system.ts
497
- var createSystemPrompt = (options = {}) => Template.process(format_default, defaultsDeep(options, {
1714
+ var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
498
1715
  DATETIME: (/* @__PURE__ */ new Date()).toISOString()
499
1716
  }));
500
1717
  var SYSTEM_ID = "01K2J2FZWH39F55CS7B26GP1Q3";
501
1718
  var templates = {
502
- system: Template.make({
1719
+ system: Template2.make({
503
1720
  id: SYSTEM_ID,
504
1721
  source: system_default
505
1722
  })
506
1723
  };
507
1724
  export {
508
- AGENT_PROCESS_KEY,
509
- AgentInputReceived,
510
- AgentRequestCompleted,
511
- AgentService_exports as AgentService,
512
- AgentTurnCompleted,
513
- AgentTurnStarted,
1725
+ AgentRequestBegin,
1726
+ AgentRequestEnd,
514
1727
  AiAssistantError,
515
- AiContextBinder,
516
- AiContextService,
517
- AiConversation,
518
- AiConversationService,
1728
+ AiContext_exports as AiContext,
519
1729
  AiModelError,
520
- AiSession,
521
- ArtifactDiffResolver,
1730
+ AiRequest_exports as AiRequest,
1731
+ AiSession_exports as AiSession,
522
1732
  ArtifactId,
523
- Bindings,
524
1733
  CompleteBlock,
525
- ContextBinding,
526
1734
  ExecutionGraph,
527
1735
  GenerationObserver,
1736
+ McpServerError,
528
1737
  PartialBlock,
529
1738
  RefFromLLM,
530
- ToolCallCompleted,
531
- ToolCallStarted,
532
1739
  ToolExecutionServices,
533
- VersionPin,
534
1740
  applyDiffs,
535
1741
  computeDiffsWithCursors,
536
1742
  createArtifactElement,
@@ -538,13 +1744,11 @@ export {
538
1744
  createToolkit,
539
1745
  formatSystemPrompt,
540
1746
  formatUserPrompt,
541
- functionInvocationServiceFromOperations,
542
1747
  getOperationFromTool,
543
1748
  makeToolExecutionService,
544
- makeToolExecutionServiceFromFunctions,
545
1749
  makeToolExecutionServiceFromOperationInvoker,
546
- makeToolResolverFromFunctions,
547
1750
  makeToolResolverFromOperations,
1751
+ mapAiError,
548
1752
  reduceDiffs,
549
1753
  templates
550
1754
  };