@dxos/assistant 0.10.0 → 0.11.1

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 (45) hide show
  1. package/dist/lib/extraction.mjs +169 -0
  2. package/dist/lib/extraction.mjs.map +1 -0
  3. package/dist/lib/index.mjs +1958 -0
  4. package/dist/lib/index.mjs.map +1 -0
  5. package/dist/types/src/request/AiRequest.d.ts +6 -3
  6. package/dist/types/src/request/AiRequest.d.ts.map +1 -1
  7. package/dist/types/src/request/AiRequest.test.d.ts +2 -0
  8. package/dist/types/src/request/AiRequest.test.d.ts.map +1 -0
  9. package/dist/types/src/request/format.d.ts +2 -2
  10. package/dist/types/src/request/format.d.ts.map +1 -1
  11. package/dist/types/src/request/format.test.d.ts +2 -0
  12. package/dist/types/src/request/format.test.d.ts.map +1 -0
  13. package/dist/types/src/session/AiContext.d.ts +1 -1
  14. package/dist/types/src/session/AiContext.d.ts.map +1 -1
  15. package/dist/types/src/session/AiSession.d.ts +25 -4
  16. package/dist/types/src/session/AiSession.d.ts.map +1 -1
  17. package/dist/types/src/session/harness-control.d.ts +4 -0
  18. package/dist/types/src/session/harness-control.d.ts.map +1 -1
  19. package/dist/types/src/tool-runtime/services.d.ts +7 -0
  20. package/dist/types/src/tool-runtime/services.d.ts.map +1 -1
  21. package/dist/types/src/tool-runtime/services.test.d.ts +2 -0
  22. package/dist/types/src/tool-runtime/services.test.d.ts.map +1 -0
  23. package/dist/types/src/util/execution-graph.d.ts.map +1 -1
  24. package/dist/types/src/util/tracing.d.ts +10 -0
  25. package/dist/types/src/util/tracing.d.ts.map +1 -1
  26. package/dist/types/tsconfig.tsbuildinfo +1 -1
  27. package/package.json +25 -25
  28. package/src/extraction/quotes.test.ts +4 -4
  29. package/src/request/AiRequest.test.ts +110 -0
  30. package/src/request/AiRequest.ts +11 -4
  31. package/src/request/format.test.ts +93 -0
  32. package/src/request/format.ts +48 -11
  33. package/src/session/AiContext.ts +1 -1
  34. package/src/session/AiSession.test.ts +124 -0
  35. package/src/session/AiSession.ts +81 -8
  36. package/src/tool-runtime/services.test.ts +41 -0
  37. package/src/tool-runtime/services.ts +16 -1
  38. package/src/util/execution-graph.ts +1 -1
  39. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
  40. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
  41. package/dist/lib/neutral/extraction/index.mjs +0 -197
  42. package/dist/lib/neutral/extraction/index.mjs.map +0 -7
  43. package/dist/lib/neutral/index.mjs +0 -2047
  44. package/dist/lib/neutral/index.mjs.map +0 -7
  45. package/dist/lib/neutral/meta.json +0 -1
@@ -1,2047 +0,0 @@
1
- import {
2
- __export
3
- } from "./chunk-J5LGTIGS.mjs";
4
-
5
- // src/tool-runtime/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 } from "@dxos/compute";
17
- import { todo } from "@dxos/debug";
18
- import { DXN, Filter, Ref as Ref2, Registry } 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 { EID, EntityId, SpaceId } from "@dxos/keys";
26
- import { trim } from "@dxos/util";
27
- var createArtifactElement = (id) => `<artifact id=${id} />`;
28
- var ArtifactURI = class extends Schema.String.annotations({
29
- // TODO(dmaretskyi): This section gets overriden.
30
- description: trim`
31
- The URI of the referenced object. Protocols accepted:
32
- - echo://01KG7R1ZXWFMWQ4DA1Q6TN1DG4.
33
- - space ID, object ID tuple (spaceID:objectID)
34
- - Only object ID that is assumed to be in the current space (01KG7R1ZXWFMWQ4DA1Q6TN1DG4)
35
- - dxn:org.dxos.type.calendar:0.1.0 -- named entity from the registry. Absoutely make sure it actually exists in the registry.
36
-
37
- URIs can be prepended with an @ symbol for compatibility with in-text references.
38
- `,
39
- examples: [
40
- "echo://01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
41
- "@echo://01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
42
- "BM3FSHFOMJCHCG5QW7JTVKGYABD2GAA7G:01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
43
- "01KG7R1ZXWFMWQ4DA1Q6TN1DG4",
44
- "dxn:org.dxos.type.calendar:0.1.0",
45
- "@dxn:org.dxos.type.calendar:0.1.0"
46
- ]
47
- }) {
48
- static toEchoURI(reference, owningSpaceId) {
49
- const stripped = reference.startsWith("@") ? reference.slice(1) : reference;
50
- if (stripped.startsWith("echo:") || stripped.startsWith("dxn:")) {
51
- return EID.parse(stripped);
52
- } else if (stripped.includes(":")) {
53
- const [spaceId, objectId] = stripped.split(":");
54
- if (!SpaceId.isValid(spaceId) || !EntityId.isValid(objectId)) {
55
- throw new Error(`Unable to parse object reference: ${reference}`);
56
- }
57
- return spaceId === owningSpaceId ? EID.make({
58
- entityId: objectId
59
- }) : EID.make({
60
- spaceId,
61
- entityId: objectId
62
- });
63
- } else if (EntityId.isValid(stripped)) {
64
- return EID.make({
65
- entityId: stripped
66
- });
67
- } else {
68
- throw new Error(`Unable to parse object reference: ${reference}`);
69
- }
70
- }
71
- /**
72
- * Resolves an artifact ID to an object.
73
- */
74
- static resolve(schema, ref) {
75
- const uri = ArtifactURI.toEchoURI(ref);
76
- return Database.resolve(Ref.fromURI(uri), schema);
77
- }
78
- };
79
- var RefFromLLM = Schema.transform(ArtifactURI, Ref.Ref(Obj.Unknown), {
80
- decode: (fromA) => {
81
- const eid = ArtifactURI.toEchoURI(fromA);
82
- return EncodedReference.fromURI(EID.toLocal(eid));
83
- },
84
- encode: (toI) => EncodedReference.toURI(toI),
85
- strict: false
86
- }).annotations({
87
- description: ArtifactURI.ast.annotations.description
88
- });
89
-
90
- // src/util/diff.ts
91
- import { next as A } from "@automerge/automerge";
92
- import { toCursorRange } from "@dxos/echo-client";
93
- import { Doc } from "@dxos/echo-doc";
94
- import { log } from "@dxos/log";
95
- import { isNonNullable } from "@dxos/util";
96
- var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/assistant/src/util/diff.ts";
97
- var reduceDiffs = (diffs) => {
98
- return diffs.reduce((acc, diff) => {
99
- const current = acc[acc.length - 1];
100
- const [op, ...rest] = diff.split(" ");
101
- switch (op) {
102
- case "-": {
103
- if (current && !current.match) {
104
- current.match += rest.join(" ");
105
- } else {
106
- acc.push({
107
- match: rest.join(" "),
108
- replace: ""
109
- });
110
- }
111
- return acc;
112
- }
113
- case "+": {
114
- if (current && !current.replace) {
115
- current.replace += rest.join(" ");
116
- } else {
117
- acc.push({
118
- match: "",
119
- replace: rest.join(" ")
120
- });
121
- }
122
- return acc;
123
- }
124
- default: {
125
- throw new Error(`Invalid diff format: each line must start with "- " or "+ ", got: ${JSON.stringify(diff)}`);
126
- }
127
- }
128
- }, []);
129
- };
130
- var computeDiffsWithCursors = (accessor, diffs) => {
131
- return reduceDiffs(diffs).map((diff) => {
132
- const text = Doc.getValue(accessor);
133
- const idx = text.indexOf(diff.match);
134
- if (idx !== -1) {
135
- return {
136
- cursor: toCursorRange(accessor, idx, idx + diff.match.length),
137
- text: diff.replace
138
- };
139
- }
140
- }).filter(isNonNullable);
141
- };
142
- var applyDiffs = (accessor, diffs, { errorOnNotFound = false } = {}) => {
143
- for (const diff of reduceDiffs(diffs)) {
144
- accessor.handle.change((doc) => {
145
- const text = Doc.getValue(accessor);
146
- const idx = text.indexOf(diff.match);
147
- if (idx !== -1) {
148
- A.splice(doc, accessor.path, idx, diff.match.length, diff.replace);
149
- } else {
150
- if (errorOnNotFound) {
151
- throw new Error(`Diff not found: ${diff.match}`);
152
- } else {
153
- log.warn("diff not found", diff, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 76, S: void 0 });
154
- }
155
- }
156
- });
157
- }
158
- return Doc.getValue(accessor);
159
- };
160
-
161
- // src/util/error-handling.ts
162
- import * as AiError from "@effect/ai/AiError";
163
- import * as HttpClientError from "@effect/platform/HttpClientError";
164
- import * as Effect from "effect/Effect";
165
- import * as Schema2 from "effect/Schema";
166
-
167
- // src/util/errors.ts
168
- import { BaseError } from "@dxos/errors";
169
- var AiModelError = class extends BaseError.extend("AiModelError", "AI model error") {
170
- };
171
- var AiAssistantError = class extends BaseError.extend("AiAssistantError", "AI assistant error") {
172
- };
173
-
174
- // src/util/error-handling.ts
175
- var AnthropicErrorResponse = Schema2.Struct({
176
- type: Schema2.Literal("error"),
177
- error: Schema2.Struct({
178
- type: Schema2.String,
179
- message: Schema2.String
180
- })
181
- });
182
- var mapAiError = (err) => Effect.gen(function* () {
183
- const cause = err.cause;
184
- if (HttpClientError.isHttpClientError(cause) && cause.reason === "StatusCode") {
185
- const body = yield* cause.response.json.pipe(Effect.flatMap(Schema2.decodeUnknown(AnthropicErrorResponse, {
186
- exact: false
187
- })));
188
- const parsedCause = new AiModelError({
189
- message: body.error.message,
190
- context: {
191
- model: "anthropic",
192
- type: body.error.type
193
- }
194
- });
195
- return AiError.UnknownError.make({
196
- description: body.error.message,
197
- module: err.module,
198
- method: err.method,
199
- cause: parsedCause
200
- });
201
- }
202
- return err;
203
- }).pipe(Effect.catchAll(() => Effect.succeed(err)));
204
-
205
- // src/util/execution-graph.ts
206
- import { AgentStatus } from "@dxos/ai";
207
- import { Obj as Obj2 } from "@dxos/echo";
208
- import { MESSAGE_PROPERTY_TOOL_CALL_ID } from "@dxos/functions";
209
- import { EID as EID2 } from "@dxos/keys";
210
- import { LogLevel } from "@dxos/log";
211
- import { ContentBlock, Message } from "@dxos/types";
212
- import { isNonNullable as isNonNullable2 } from "@dxos/util";
213
- var SKIP_BLOCKS = [
214
- "text"
215
- ];
216
- var ExecutionGraph = class {
217
- _skipBlocks;
218
- // TODO(dmaretskyi): Evolve the internal state to support chats, functions, circuit workflows, etc.
219
- _commits = [];
220
- _branchNames = /* @__PURE__ */ new Set();
221
- _lastBlockId;
222
- // Tool call tracking.
223
- _toolCallCommitIds = /* @__PURE__ */ new Map();
224
- _lastCommitByBranch = /* @__PURE__ */ new Map();
225
- _pendingToolResults = /* @__PURE__ */ new Map();
226
- constructor(_skipBlocks = SKIP_BLOCKS) {
227
- this._skipBlocks = _skipBlocks;
228
- }
229
- /**
230
- * Adds events to the graph.
231
- */
232
- addEvents(events) {
233
- const sortedEvents = this.sortObjectsByCreated(events);
234
- for (const event of sortedEvents) {
235
- if (Obj2.instanceOf(Message.Message, event)) {
236
- this._processMessage(event);
237
- } else if (Obj2.instanceOf(AgentStatus, event)) {
238
- this._processAgentStatus(event);
239
- }
240
- }
241
- }
242
- /**
243
- * Processes a message event and creates commits for its blocks.
244
- */
245
- _processMessage(message) {
246
- const messageCommits = messageToCommits(message, this._lastBlockId, this._toolCallCommitIds, this._lastCommitByBranch, this._skipBlocks);
247
- this._commits.push(...messageCommits);
248
- messageCommits.forEach((commit) => this._branchNames.add(commit.branch));
249
- this._trackToolCalls(messageCommits);
250
- if (messageCommits.length > 0) {
251
- this._lastBlockId = messageCommits[messageCommits.length - 1].id;
252
- }
253
- }
254
- /**
255
- * Processes an AgentStatus event.
256
- */
257
- _processAgentStatus(event) {
258
- const branch = this._getToolCallBranch(event.parentMessage, event.toolCallId);
259
- this._branchNames.add(branch);
260
- const agentStatusCommit = {
261
- id: event.id,
262
- branch,
263
- message: event.message,
264
- icon: "ph--flag--regular",
265
- parents: this._getAgentStatusParents(event),
266
- timestamp: new Date(event.created)
267
- };
268
- this._commits.push(agentStatusCommit);
269
- this._lastBlockId = event.id;
270
- if (event.toolCallId) {
271
- this._lastCommitByBranch.set(branch, event.id);
272
- this._updatePendingToolResults(event.toolCallId, event.id);
273
- }
274
- }
275
- /**
276
- * Stable sort: objects with 'created' field are sorted by it, others remain in place.
277
- */
278
- sortObjectsByCreated(objects) {
279
- const sortedObjects = objects.slice();
280
- const createdObjects = [];
281
- sortedObjects.forEach((obj, idx) => {
282
- if (obj && typeof obj.created === "string") {
283
- createdObjects.push({
284
- idx,
285
- obj
286
- });
287
- }
288
- });
289
- createdObjects.sort((a, b) => {
290
- const aDate = new Date(a.obj.created).getTime();
291
- const bDate = new Date(b.obj.created).getTime();
292
- return aDate - bDate;
293
- });
294
- let createdIdx = 0;
295
- return sortedObjects.map((obj, _idx) => {
296
- if (obj && typeof obj.created === "string") {
297
- return createdObjects[createdIdx++].obj;
298
- }
299
- return obj;
300
- });
301
- }
302
- /**
303
- * Returns the current state of the graph.
304
- */
305
- getGraph(lastRequest = false) {
306
- const idx = lastRequest ? this._commits.findLastIndex((c) => c.tags?.includes("user")) : -1;
307
- const commits = idx === -1 ? this._commits : this._commits.slice(idx);
308
- return {
309
- branches: Array.from(this._branchNames),
310
- commits
311
- };
312
- }
313
- /**
314
- * Tracks tool calls and handles pending tool result updates.
315
- */
316
- _trackToolCalls(commits) {
317
- commits.forEach((commit) => {
318
- if (this._isToolCallCommit(commit)) {
319
- const toolCallId = this._extractToolCallId(commit.id);
320
- if (toolCallId) {
321
- this._toolCallCommitIds.set(toolCallId, commit.id);
322
- }
323
- }
324
- if (this._isToolResultCommit(commit)) {
325
- const toolCallId = this._extractToolCallId(commit.id);
326
- if (toolCallId) {
327
- this._pendingToolResults.set(toolCallId, commit.id);
328
- this._handleLateToolResultUpdate(toolCallId, commit.id);
329
- }
330
- }
331
- this._lastCommitByBranch.set(commit.branch, commit.id);
332
- });
333
- }
334
- /**
335
- * Updates pending tool results to point to an AgentStatus event.
336
- */
337
- _updatePendingToolResults(toolCallId, agentStatusId) {
338
- const toolResultId = this._pendingToolResults.get(toolCallId);
339
- if (!toolResultId) {
340
- return;
341
- }
342
- const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
343
- if (!toolResultCommit) {
344
- return;
345
- }
346
- const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
347
- if (!toolCallCommitId) {
348
- return;
349
- }
350
- const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
351
- if (toolCallIndex !== -1) {
352
- toolResultCommit.parents[toolCallIndex] = agentStatusId;
353
- }
354
- this._pendingToolResults.delete(toolCallId);
355
- }
356
- /**
357
- * Handles late updates when AgentStatus is processed before tool result.
358
- */
359
- _handleLateToolResultUpdate(toolCallId, toolResultId) {
360
- const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);
361
- if (!toolCallCommitId) {
362
- return;
363
- }
364
- const messageId = toolCallCommitId.split("_toolCall_")[0];
365
- const toolCallBranch = `${messageId}_${toolCallId}`;
366
- const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);
367
- if (agentStatusCommitId && agentStatusCommitId !== toolCallCommitId) {
368
- const toolResultCommit = this._commits.find((c) => c.id === toolResultId);
369
- if (toolResultCommit) {
370
- const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);
371
- if (toolCallIndex !== -1) {
372
- toolResultCommit.parents[toolCallIndex] = agentStatusCommitId;
373
- }
374
- }
375
- this._pendingToolResults.delete(toolCallId);
376
- }
377
- }
378
- /**
379
- * Gets the branch name for a tool call.
380
- */
381
- _getToolCallBranch(parentMessage, toolCallId) {
382
- if (toolCallId) {
383
- return toolCallId;
384
- }
385
- return parentMessage || "main";
386
- }
387
- /**
388
- * Gets the parents for an AgentStatus commit.
389
- */
390
- _getAgentStatusParents(event) {
391
- if (event.parentMessage && event.toolCallId) {
392
- return [
393
- getToolCallId(event.parentMessage, event.toolCallId)
394
- ];
395
- }
396
- return [];
397
- }
398
- /**
399
- * Checks if a commit is a tool call commit.
400
- */
401
- _isToolCallCommit(commit) {
402
- return commit.message.includes("Calling tool");
403
- }
404
- /**
405
- * Checks if a commit is a tool result commit.
406
- */
407
- _isToolResultCommit(commit) {
408
- return commit.message.includes("Tool call succeeded") || commit.message.includes("Tool error:");
409
- }
410
- /**
411
- * Extracts tool call ID from a commit ID.
412
- */
413
- _extractToolCallId(commitId) {
414
- const toolCallMatch = commitId.match(/_toolCall_(.+)$/);
415
- const toolResultMatch = commitId.match(/_toolResult_(.+)$/);
416
- return toolCallMatch?.[1] || toolResultMatch?.[1];
417
- }
418
- };
419
- var messageToCommits = (message, lastBlockId, toolCallIds, lastCommitByBranch, skipBlocks) => {
420
- let previousBlockId = lastBlockId;
421
- return message.blocks.map((block, idx) => {
422
- const branch = getMessageBranch(message);
423
- const parents = getBlockParents(block, previousBlockId, message, toolCallIds, lastCommitByBranch);
424
- if (skipBlocks?.includes(block._tag)) {
425
- return null;
426
- }
427
- const commit = createBlockCommit(block, message, branch, parents, idx);
428
- if (commit) {
429
- previousBlockId = commit.id;
430
- }
431
- return commit;
432
- }).filter(isNonNullable2);
433
- };
434
- var getBlockParents = (block, previousBlockId, message, toolCallIds, lastCommitByBranch) => {
435
- const parents = [];
436
- if (block._tag === "toolResult") {
437
- if (previousBlockId) {
438
- parents.push(previousBlockId);
439
- }
440
- const toolCallCommitId = toolCallIds?.get(block.toolCallId);
441
- if (toolCallCommitId) {
442
- const toolCallBranch = getToolCallBranchFromCommitId(toolCallCommitId, block.toolCallId);
443
- const lastBlockFromToolCallBranch = lastCommitByBranch?.get(toolCallBranch);
444
- if (lastBlockFromToolCallBranch) {
445
- parents.push(lastBlockFromToolCallBranch);
446
- } else {
447
- parents.push(toolCallCommitId);
448
- }
449
- }
450
- } else {
451
- if (previousBlockId) {
452
- parents.push(previousBlockId);
453
- } else {
454
- const toolCallParent = getParentId(message);
455
- if (toolCallParent) {
456
- parents.push(toolCallParent);
457
- }
458
- }
459
- }
460
- return parents;
461
- };
462
- var createBlockCommit = (block, message, branch, parents, idx) => {
463
- const timestamp = new Date(message.created);
464
- switch (block._tag) {
465
- case "text":
466
- if (!block.text.trim().length) {
467
- return null;
468
- }
469
- return {
470
- id: getGenericBlockId(message.id, idx),
471
- branch,
472
- parents,
473
- timestamp,
474
- ...message.sender.role === "user" ? {
475
- icon: "ph--user--regular",
476
- tags: [
477
- "user"
478
- ],
479
- message: "Processing request..."
480
- } : {
481
- icon: "ph--drone--regular",
482
- message: `Response (${block.text.split(" ").length} words)`
483
- }
484
- };
485
- case "toolCall":
486
- return {
487
- id: getToolCallId(message.id, block.toolCallId),
488
- branch,
489
- parents,
490
- timestamp,
491
- icon: "ph--wrench--regular",
492
- level: LogLevel.INFO,
493
- message: `Calling tool (${block.name})`
494
- };
495
- case "toolResult":
496
- return {
497
- id: getToolResultId(message.id, block.toolCallId),
498
- branch,
499
- parents,
500
- timestamp,
501
- icon: block.error ? "ph--x-circle--regular" : "ph--check-circle--regular",
502
- level: block.error ? LogLevel.ERROR : LogLevel.INFO,
503
- message: block.error ? "Tool error: " + block.error : "Tool call succeeded"
504
- };
505
- case "stats":
506
- return {
507
- id: getGenericBlockId(message.id, idx),
508
- branch,
509
- parents,
510
- timestamp,
511
- icon: "ph--rocket--regular",
512
- level: LogLevel.INFO,
513
- message: ContentBlock.createStatsMessage(block)
514
- };
515
- case "status":
516
- return {
517
- id: getGenericBlockId(message.id, idx),
518
- branch,
519
- parents,
520
- timestamp,
521
- message: block.statusText,
522
- level: LogLevel.INFO,
523
- icon: "ph--flag--regular"
524
- };
525
- case "reasoning":
526
- return {
527
- id: getGenericBlockId(message.id, idx),
528
- branch,
529
- parents,
530
- timestamp,
531
- message: block.reasoningText ?? "Thinking...",
532
- icon: "ph--brain--regular"
533
- };
534
- case "reference":
535
- return {
536
- id: getGenericBlockId(message.id, idx),
537
- branch,
538
- parents,
539
- timestamp,
540
- icon: "ph--link--regular",
541
- message: stringifyRef(block.reference)
542
- };
543
- default:
544
- return null;
545
- }
546
- };
547
- var getToolCallBranchFromCommitId = (toolCallCommitId, toolCallId) => {
548
- const messageId = toolCallCommitId.split("_toolCall_")[0];
549
- return `${messageId}_${toolCallId}`;
550
- };
551
- var getToolCallId = (messageId, toolCallId) => `${messageId}_toolCall_${toolCallId}`;
552
- var getToolResultId = (messageId, toolCallId) => `${messageId}_toolResult_${toolCallId}`;
553
- var getGenericBlockId = (messageId, idx) => `${messageId}_block_${idx}`;
554
- var getBranchName = (options) => {
555
- if (options.toolCallId) {
556
- return options.toolCallId;
557
- } else if (options.parentMessage) {
558
- return options.parentMessage;
559
- } else {
560
- return "main";
561
- }
562
- };
563
- var getMessageBranch = (message) => {
564
- return getBranchName({
565
- parentMessage: message.parentMessage,
566
- toolCallId: message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]
567
- });
568
- };
569
- var getParentId = (message) => {
570
- if (message.parentMessage && message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]) {
571
- return getToolCallId(message.parentMessage, message.properties[MESSAGE_PROPERTY_TOOL_CALL_ID]);
572
- } else {
573
- return void 0;
574
- }
575
- };
576
- var stringifyRef = (ref) => {
577
- if (ref.target) {
578
- return stringifyObject(ref.target);
579
- }
580
- const echoUri = EID2.tryParse(ref.uri);
581
- return (echoUri ? EID2.getEntityId(echoUri) : void 0) ?? "";
582
- };
583
- var stringifyObject = (obj) => {
584
- return Obj2.getLabel(obj) ?? Obj2.getTypename(obj) ?? obj.id;
585
- };
586
-
587
- // src/util/tracing.ts
588
- import * as Schema3 from "effect/Schema";
589
- import { Trace } from "@dxos/compute";
590
- import { Obj as Obj3 } from "@dxos/echo";
591
- import { Actor, ContentBlock as ContentBlock2 } from "@dxos/types";
592
- var PartialBlock = Trace.EventType("assistant.partialBlock", {
593
- schema: Schema3.Struct({
594
- messageId: Obj3.ID,
595
- role: Actor.Role,
596
- block: ContentBlock2.Any
597
- }),
598
- isEphemeral: true
599
- });
600
- var CompleteBlock = Trace.EventType("assistant.completeBlock", {
601
- schema: Schema3.Struct({
602
- messageId: Obj3.ID,
603
- role: Actor.Role,
604
- block: ContentBlock2.Any
605
- }),
606
- isEphemeral: false
607
- });
608
- var AgentRequestBegin = Trace.EventType("assistant.agentRequestBegin", {
609
- schema: Schema3.Struct({}),
610
- isEphemeral: false
611
- });
612
- var AgentRequestEnd = Trace.EventType("assistant.agentRequestEnd", {
613
- schema: Schema3.Struct({
614
- status: Schema3.Literal("success", "error", "interrupted"),
615
- error: Schema3.optional(Schema3.String)
616
- }),
617
- isEphemeral: false
618
- });
619
- var McpServerError = Trace.EventType("assistant.mcpServerError", {
620
- schema: Schema3.Struct({
621
- url: Schema3.String,
622
- protocol: Schema3.Literal("sse", "http"),
623
- message: Schema3.String
624
- }),
625
- isEphemeral: true
626
- });
627
-
628
- // src/tool-runtime/services.ts
629
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/compute/assistant/src/tool-runtime/services.ts";
630
- var makeToolResolverFromOperations = ({ toolkit: extraToolkit = OpaqueToolkit.empty } = {}) => {
631
- return Layer.effect(ToolResolverService, Effect2.gen(function* () {
632
- const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
633
- const registry = yield* Registry.Service;
634
- return {
635
- resolve: (id) => Effect2.gen(function* () {
636
- const toolkit = OpaqueToolkit.merge(extraToolkit, toolkitProvider.getToolkit());
637
- const tool = toolkit.toolkit.tools[id];
638
- if (tool) {
639
- return tool;
640
- }
641
- const key = DXN.isDXN(id) ? id : `dxn:${id}`;
642
- const results = yield* Effect2.promise(() => registry.query(Filter.and(Filter.type(Operation.PersistentOperation), Filter.key(key))).run());
643
- if (results.length > 0) {
644
- return projectFunctionToTool(Operation.deserialize(results[0]));
645
- }
646
- return yield* Effect2.fail(new AiToolNotFoundError(id));
647
- })
648
- };
649
- }));
650
- };
651
- var makeToolExecutionService = (opts) => Layer.effect(ToolExecutionService, Effect2.gen(function* () {
652
- const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;
653
- const toolkit = toolkitProvider.getToolkit();
654
- const toolkitHandler = yield* toolkit.toolkit.pipe(Effect2.provide(toolkit.layer));
655
- invariant(isHandlerLike(toolkitHandler), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 45, S: this, A: ["isHandlerLike(toolkitHandler)", ""] });
656
- return {
657
- handlersFor: (toolkit2) => {
658
- const makeHandler = (tool) => {
659
- return Effect2.fn(`toolFunctionHandler ${tool.name}`)(function* (input) {
660
- if (toolkitHandler.tools[tool.name]) {
661
- if (Tool.isProviderDefined(tool)) {
662
- throw new Error("Attempted to call a provider-defined tool");
663
- }
664
- const { result } = yield* toolkitHandler.handle(tool.name, input);
665
- return result;
666
- }
667
- return yield* opts.invoke(tool, input).pipe(Effect2.catchAllDefect((defect) => Effect2.fail(defect)));
668
- });
669
- };
670
- return toolkit2.of(Record.map(toolkit2.tools, (tool, _name) => Tool.isUserDefined(tool) ? makeHandler(tool) : null));
671
- }
672
- };
673
- }));
674
- var makeToolExecutionServiceFromOperationInvoker = () => {
675
- return Layer.unwrapEffect(Effect2.gen(function* () {
676
- const operationInvoker = yield* Operation.Service;
677
- return makeToolExecutionService({
678
- invoke: (tool, input) => Effect2.gen(function* () {
679
- const operationDef = getOperationFromTool(tool).pipe(Option.getOrThrow);
680
- return yield* operationInvoker.invoke(operationDef, input).pipe(Effect2.orDie);
681
- })
682
- });
683
- }));
684
- };
685
- var ToolExecutionServices = Layer.mergeAll(makeToolResolverFromOperations(), makeToolExecutionServiceFromOperationInvoker());
686
- var FunctionToolAnnotation = class extends Context.Tag("@dxos/assistant/FunctionToolAnnotation")() {
687
- };
688
- var getOperationFromTool = (tool) => {
689
- return Context.getOption(FunctionToolAnnotation)(tool.annotations).pipe(Option.map(({ definition }) => definition));
690
- };
691
- var toolCache = /* @__PURE__ */ new WeakMap();
692
- var EMPTY_PARAMETERS_SCHEMA = Schema4.Struct({}).annotations({
693
- [SchemaAST.JSONSchemaAnnotationId]: {
694
- type: "object",
695
- properties: {},
696
- required: [],
697
- additionalProperties: false
698
- }
699
- });
700
- var projectFunctionToTool = (fn2) => {
701
- if (toolCache.has(fn2)) {
702
- return toolCache.get(fn2);
703
- }
704
- const fields = createStructFieldsFromSchema(fn2.input);
705
- const parametersSchema = Object.keys(fields).length === 0 ? EMPTY_PARAMETERS_SCHEMA : Schema4.Struct(fields);
706
- const tool = Tool.make(makeToolName(fn2.meta.name ?? fn2.meta.key), {
707
- description: fn2.meta.description,
708
- failure: Schema4.Any
709
- }).setParameters(parametersSchema).annotate(FunctionToolAnnotation, {
710
- definition: fn2
711
- });
712
- toolCache.set(fn2, tool);
713
- return tool;
714
- };
715
- var makeToolName = (name) => {
716
- const toolName = name.toLowerCase().replace(/[^a-zA-Z0-9]/g, "-");
717
- invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 117, S: void 0, A: ["toolName.match(/^[a-z_][a-z0-9-_]*$/)", ""] });
718
- return toolName;
719
- };
720
- var createStructFieldsFromSchema = (schema) => {
721
- switch (schema.ast._tag) {
722
- case "TypeLiteral":
723
- return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [
724
- prop.name,
725
- Schema4.make(mapSchemaTypeForLLM(prop.type))
726
- ]));
727
- case "VoidKeyword":
728
- return {};
729
- default:
730
- return todo(`Unsupported schema AST: ${schema.ast._tag}`);
731
- }
732
- };
733
- var mapSchemaTypeForLLM = (ast) => {
734
- if (Ref2.isRefType(ast)) {
735
- const description = ast.annotations.description ? ast.annotations.description + "\n" + RefFromLLM.ast.annotations.description : RefFromLLM.ast.annotations.description;
736
- return RefFromLLM.annotations({
737
- description
738
- }).ast;
739
- } else if (SchemaAST.isTupleType(ast)) {
740
- 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);
741
- } else if (SchemaAST.isTypeLiteral(ast)) {
742
- 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);
743
- }
744
- return ast;
745
- };
746
- var isHandlerLike = (value) => {
747
- return typeof value.tools === "object" && typeof value.handle === "function";
748
- };
749
-
750
- // src/request/format.ts
751
- import * as Effect3 from "effect/Effect";
752
- import * as Function from "effect/Function";
753
- import * as Option2 from "effect/Option";
754
- import { Template } from "@dxos/compute";
755
- import { Obj as Obj4 } from "@dxos/echo";
756
- import { ObjectVersion } from "@dxos/echo-client";
757
- import { log as log2 } from "@dxos/log";
758
- import { Message as Message2 } from "@dxos/types";
759
- import { trim as trim2 } from "@dxos/util";
760
-
761
- // src/request/artifact-diff.ts
762
- import * as Context2 from "effect/Context";
763
- var ArtifactDiffResolver = class extends Context2.Tag("@dxos/assistant/ArtifactDiffResolver")() {
764
- };
765
-
766
- // src/request/format.ts
767
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/compute/assistant/src/request/format.ts";
768
- var formatSystemPrompt = ({ system, skills = [], objects = [] }) => Effect3.gen(function* () {
769
- const skillDefs = yield* Function.pipe(skills, Effect3.forEach((skill) => Effect3.succeed(skill.instructions)), Effect3.flatMap(Effect3.forEach((template) => Effect3.gen(function* () {
770
- return trim2`
771
- <skill>
772
- ${yield* Template.processTemplate(template)}
773
- </skill>
774
- `;
775
- }))), Effect3.map((skills2) => skills2.length > 0 ? [
776
- "## Skills Definitions",
777
- ...skills2
778
- ].join("\n\n") : void 0));
779
- const objectDefs = yield* Function.pipe(objects, Effect3.forEach((object) => Effect3.succeed(trim2`
780
- <object>
781
- <dxn>${Obj4.getURI(object)}</dxn>
782
- <typename>${Obj4.getTypename(object)}</typename>
783
- </object>
784
- `)), Effect3.map((objects2) => objects2.length > 0 ? [
785
- "## Context Objects",
786
- ...objects2
787
- ].join("\n\n") : void 0));
788
- return yield* Function.pipe(Effect3.succeed([
789
- system,
790
- skillDefs,
791
- objectDefs
792
- ].filter((def) => def !== void 0)), Effect3.map((parts) => parts.join("\n\n")));
793
- }).pipe(Effect3.withSpan("formatSystemPrompt"));
794
- var formatUserPrompt = ({ prompt, history: history2 = [] }) => Effect3.gen(function* () {
795
- const blocks = [];
796
- const artifactDiffResolver = yield* Effect3.serviceOption(ArtifactDiffResolver);
797
- if (Option2.isSome(artifactDiffResolver)) {
798
- const versions = gatherObjectVersions(history2);
799
- const artifactDiff = yield* Effect3.tryPromise({
800
- try: () => artifactDiffResolver.value.resolve([
801
- ...versions.entries()
802
- ].map(([id, version]) => ({
803
- id,
804
- lastVersion: version
805
- }))),
806
- catch: AiAssistantError.wrap({
807
- message: "Artifact diff resolution error"
808
- })
809
- });
810
- log2("version", {
811
- artifactDiff,
812
- versions
813
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 65, S: this });
814
- for (const [id, { version }] of [
815
- ...artifactDiff.entries()
816
- ]) {
817
- if (ObjectVersion.equals(version, versions.get(id))) {
818
- artifactDiff.delete(id);
819
- continue;
820
- }
821
- blocks.push({
822
- _tag: "anchor",
823
- objectId: id,
824
- version
825
- });
826
- }
827
- if (artifactDiff.size > 0) {
828
- blocks.push(createArtifactUpdateBlock(artifactDiff));
829
- }
830
- }
831
- return Obj4.make(Message2.Message, {
832
- created: (/* @__PURE__ */ new Date()).toISOString(),
833
- sender: {
834
- role: "user"
835
- },
836
- blocks: typeof prompt === "string" ? [
837
- ...blocks,
838
- {
839
- _tag: "text",
840
- text: prompt
841
- }
842
- ] : [
843
- ...blocks,
844
- ...prompt
845
- ]
846
- });
847
- }).pipe(Effect3.withSpan("formatUserPrompt"));
848
- var gatherObjectVersions = (messages) => {
849
- const artifactIds = /* @__PURE__ */ new Map();
850
- for (const message of messages) {
851
- for (const block of message.blocks) {
852
- if (block._tag === "anchor") {
853
- artifactIds.set(block.objectId, block.version);
854
- }
855
- }
856
- }
857
- return artifactIds;
858
- };
859
- var createArtifactUpdateBlock = (artifactDiff) => {
860
- return {
861
- _tag: "text",
862
- // TODO(dmaretskyi): Does this need to be a special content-block?
863
- disposition: "synthetic",
864
- text: trim2`
865
- The following artifacts have been updated since the last message:
866
- ${[
867
- ...artifactDiff.entries()
868
- ].map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
869
- ${diff}` : ""}</changed-artifact>`).join("\n")}
870
- `
871
- };
872
- };
873
-
874
- // src/request/observer.ts
875
- import * as Effect4 from "effect/Effect";
876
- import * as Function2 from "effect/Function";
877
- var GenerationObserver = Object.freeze({
878
- 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) } = {}) => ({
879
- onBegin,
880
- onPart,
881
- onBlock,
882
- onEnd,
883
- onMessage
884
- }),
885
- noop: () => GenerationObserver.make(),
886
- /**
887
- * Debug printer to be used in unit-tests and browser devtools.
888
- */
889
- fromPrinter: (printer) => GenerationObserver.make({
890
- onBlock: (block) => Effect4.sync(() => {
891
- if (block.pending) {
892
- return;
893
- }
894
- printer.printContentBlock(block);
895
- }),
896
- onMessage: (message) => Effect4.sync(() => {
897
- if (message.sender.role === "assistant") {
898
- return;
899
- }
900
- printer.printMessage(message);
901
- })
902
- })
903
- });
904
-
905
- // src/request/AiRequest.ts
906
- var AiRequest_exports = {};
907
- __export(AiRequest_exports, {
908
- Request: () => Request
909
- });
910
- import * as LanguageModel from "@effect/ai/LanguageModel";
911
- import * as Array2 from "effect/Array";
912
- import * as Chunk from "effect/Chunk";
913
- import * as Effect5 from "effect/Effect";
914
- import { pipe as pipe2 } from "effect/Function";
915
- import * as Option3 from "effect/Option";
916
- import * as Stream from "effect/Stream";
917
- import { AiParser, AiPreprocessor, AiSummarizer, callTool, withoutToolCallParising } from "@dxos/ai";
918
- import { Trace as Trace2 } from "@dxos/compute";
919
- import { Obj as Obj5 } from "@dxos/echo";
920
- import { log as log3 } from "@dxos/log";
921
- import { ContentBlock as ContentBlock3, Message as Message3 } from "@dxos/types";
922
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/compute/assistant/src/request/AiRequest.ts";
923
- var Request = class {
924
- _options;
925
- /** Prevents concurrent execution of session. */
926
- _semaphore = Effect5.runSync(Effect5.makeSemaphore(1));
927
- _observer;
928
- _onOutput;
929
- /** Message history from queue. */
930
- // TODO(burdon): Evolve into supporting a git-like graph of messages.
931
- _history = [];
932
- /** Pending messages for this session (incl. the current prompt). */
933
- _pending = [];
934
- _started = 0;
935
- _ended = 0;
936
- _toolCalls = 0;
937
- constructor(_options = {}) {
938
- this._options = _options;
939
- this._observer = _options.observer ?? GenerationObserver.noop();
940
- this._onOutput = _options.onOutput ?? (() => Effect5.void);
941
- }
942
- get duration() {
943
- return this._ended - this._started;
944
- }
945
- get toolCalls() {
946
- return this._toolCalls;
947
- }
948
- get pending() {
949
- return this._pending;
950
- }
951
- _submitMessage = (message) => Effect5.gen(this, function* () {
952
- this._pending.push(message);
953
- yield* this._observer.onMessage(message);
954
- if (this._options.persist === false) {
955
- return message;
956
- }
957
- for (const block of message.blocks) {
958
- log3("write complete block", {
959
- messageId: message.id,
960
- role: message.sender.role,
961
- block: JSON.stringify(block)
962
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 62, S: this });
963
- yield* Trace2.write(CompleteBlock, {
964
- messageId: message.id,
965
- role: message.sender.role,
966
- block
967
- });
968
- }
969
- yield* this._onOutput(message);
970
- return message;
971
- });
972
- getToolCalls = () => pipe2([
973
- ...this._history,
974
- ...this._pending
975
- ], Array2.reverse, Array2.takeWhile((_) => _.sender.role === "assistant"), Array2.flatMap((_) => _.blocks.filter(ContentBlock3.is("toolCall")).map((block) => ({
976
- block,
977
- message: _
978
- }))), Array2.filter((_) => !_.block.providerExecuted), Array2.reverse);
979
- /**
980
- * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
981
- * Must be called before `runTurn()`.
982
- */
983
- begin = ({ prompt, system, history: history2 = [], skills = [], objects = [] }) => Effect5.gen(this, function* () {
984
- this._started = Date.now();
985
- this._history = [
986
- ...history2
987
- ];
988
- this._pending = [];
989
- const systemPrompt = yield* formatSystemPrompt({
990
- system,
991
- skills,
992
- objects
993
- }).pipe(Effect5.orDie);
994
- if (this._options.summarizationThreshold !== void 0) {
995
- const tokenCount = yield* AiPreprocessor.estimateTokens(yield* AiPreprocessor.preprocessPrompt([
996
- ...this._history
997
- ], {
998
- system: systemPrompt
999
- }));
1000
- if (tokenCount > this._options.summarizationThreshold) {
1001
- const summary = yield* AiSummarizer.summarize([
1002
- ...this._history
1003
- ]);
1004
- yield* this._submitMessage(summary);
1005
- }
1006
- }
1007
- yield* this._submitMessage(yield* formatUserPrompt({
1008
- prompt,
1009
- history: history2
1010
- }));
1011
- }).pipe(Effect5.withSpan("AiRequest.begin"));
1012
- /**
1013
- * Execute a single turn: one LLM generation followed by tool execution.
1014
- * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled skills).
1015
- */
1016
- runAgentTurn = ({ system, toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
1017
- log3("request", {
1018
- system: {
1019
- snippet: createSnippet(system),
1020
- length: system.length
1021
- },
1022
- pending: this._pending.length,
1023
- history: this._history.length
1024
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 119, S: this });
1025
- const prompt = yield* AiPreprocessor.preprocessPrompt([
1026
- ...this._history,
1027
- ...this._pending
1028
- ], {
1029
- system,
1030
- cacheControl: "ephemeral"
1031
- });
1032
- const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
1033
- const observer = this._observer;
1034
- let currentMessageId = null;
1035
- let finishReason;
1036
- const messages = yield* LanguageModel.streamText({
1037
- prompt,
1038
- toolkit,
1039
- disableToolCallResolution: true
1040
- }).pipe(withoutToolCallParising, AiParser.parseResponse({
1041
- emitPartial: true,
1042
- onBegin: () => observer.onBegin(),
1043
- onBlock: (block) => observer.onBlock(block),
1044
- onPart: (part) => observer.onPart(part),
1045
- onEnd: (summary) => observer.onEnd(summary)
1046
- }), Stream.map((block) => enrichToolCallBlock(block, toolkit)), Stream.mapEffect((block) => Effect5.gen(this, function* () {
1047
- if (block._tag === "stats" && block.finishReason !== void 0) {
1048
- finishReason = block.finishReason;
1049
- }
1050
- if (block.pending) {
1051
- currentMessageId ??= Obj5.ID.random();
1052
- log3("emit ephemeral message", {
1053
- id: currentMessageId,
1054
- type: block._tag
1055
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 154, S: this });
1056
- yield* Trace2.write(PartialBlock, {
1057
- messageId: currentMessageId,
1058
- role: "assistant",
1059
- block
1060
- });
1061
- return Option3.none();
1062
- } else {
1063
- currentMessageId ??= Obj5.ID.random();
1064
- const id = currentMessageId;
1065
- currentMessageId = null;
1066
- log3("emit complete message", {
1067
- id,
1068
- type: block._tag
1069
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 168, S: this });
1070
- const message = Obj5.make(Message3.Message, {
1071
- id,
1072
- created: (/* @__PURE__ */ new Date()).toISOString(),
1073
- sender: {
1074
- role: "assistant"
1075
- },
1076
- blocks: [
1077
- block
1078
- ]
1079
- });
1080
- return Option3.some(yield* this._submitMessage(message));
1081
- }
1082
- }), {
1083
- concurrency: 1,
1084
- unordered: false
1085
- }), Stream.filterMap((_) => _), Stream.runCollect, Effect5.map(Chunk.toArray));
1086
- log3("messages", {
1087
- messages
1088
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 188, S: this });
1089
- if (finishReason === "pause") {
1090
- return {
1091
- messages,
1092
- done: false,
1093
- finishReason
1094
- };
1095
- }
1096
- const toolCalls = this.getToolCalls();
1097
- if (toolCalls.length === 0) {
1098
- this._ended = Date.now();
1099
- return {
1100
- messages,
1101
- done: true,
1102
- finishReason
1103
- };
1104
- } else if (!toolkit) {
1105
- throw new Error("No toolkit provided");
1106
- }
1107
- return {
1108
- messages,
1109
- done: false,
1110
- finishReason
1111
- };
1112
- }).pipe(Effect5.withSpan("AiRequest.runAgentTurn"));
1113
- runTools = ({ toolkit: opaqueToolkit }) => Effect5.gen(this, function* () {
1114
- const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : void 0;
1115
- const toolCalls = this.getToolCalls();
1116
- const toolResults = yield* Effect5.forEach(toolCalls, ({ block, message }) => {
1117
- if (!toolkit) {
1118
- throw new Error("No toolkit provided");
1119
- }
1120
- return callTool(toolkit, block);
1121
- });
1122
- yield* this._submitMessage(Obj5.make(Message3.Message, {
1123
- created: (/* @__PURE__ */ new Date()).toISOString(),
1124
- sender: {
1125
- role: "tool"
1126
- },
1127
- blocks: toolResults
1128
- }));
1129
- this._toolCalls += toolResults.length;
1130
- }).pipe(Effect5.withSpan("AiRequest.runTools"));
1131
- /**
1132
- * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
1133
- */
1134
- run = ({ prompt, system: systemTemplate, history: history2 = [], objects = [], skills = [], toolkit }) => Effect5.gen(this, function* () {
1135
- yield* this.begin({
1136
- prompt,
1137
- system: systemTemplate,
1138
- history: history2,
1139
- objects,
1140
- skills
1141
- });
1142
- const system = yield* formatSystemPrompt({
1143
- system: systemTemplate,
1144
- skills,
1145
- objects
1146
- }).pipe(Effect5.orDie);
1147
- do {
1148
- const { done, finishReason } = yield* this.runAgentTurn({
1149
- system,
1150
- toolkit
1151
- });
1152
- if (done) {
1153
- break;
1154
- }
1155
- if (finishReason === "pause") {
1156
- continue;
1157
- }
1158
- yield* this.runTools({
1159
- toolkit
1160
- });
1161
- } while (true);
1162
- log3("done", {
1163
- pending: this._pending.length,
1164
- duration: this.duration,
1165
- tools: this._toolCalls
1166
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 267, S: this });
1167
- return this._pending;
1168
- }).pipe(this._semaphore.withPermits(1), Effect5.withSpan("AiRequest.run"));
1169
- };
1170
- var enrichToolCallBlock = (block, toolkit) => {
1171
- if (block._tag !== "toolCall" || !toolkit) {
1172
- return block;
1173
- }
1174
- const tool = toolkit.tools[block.name];
1175
- if (!tool) {
1176
- return block;
1177
- }
1178
- let operationOpt;
1179
- try {
1180
- operationOpt = getOperationFromTool(tool);
1181
- } catch {
1182
- return block;
1183
- }
1184
- if (Option3.isNone(operationOpt)) {
1185
- return block;
1186
- }
1187
- const { meta } = operationOpt.value;
1188
- return {
1189
- ...block,
1190
- operationKey: meta.key,
1191
- operationName: meta.name,
1192
- operationIcon: meta.icon
1193
- };
1194
- };
1195
- var createSnippet = (text, len = 32) => text.length <= len * 2 ? text : [
1196
- text.slice(0, len),
1197
- "...",
1198
- text.slice(-len)
1199
- ].join("");
1200
-
1201
- // src/session/toolkit.ts
1202
- import * as Toolkit from "@effect/ai/Toolkit";
1203
- import * as Effect6 from "effect/Effect";
1204
- import * as Layer2 from "effect/Layer";
1205
- import { OpaqueToolkit as OpaqueToolkit2, ToolExecutionService as ToolExecutionService2, ToolResolverService as ToolResolverService2 } from "@dxos/ai";
1206
- import { isTruthy } from "@dxos/util";
1207
- var createToolkit = ({ toolkit: toolkitProp, skills = [], opaqueToolkits = [] }) => Effect6.gen(function* () {
1208
- const skillToolkit = yield* ToolResolverService2.resolveToolkit(skills.flatMap(({ tools }) => tools));
1209
- const skillToolHandler = yield* skillToolkit.toContext(ToolExecutionService2.handlersFor(skillToolkit));
1210
- const opaqueToolkit = OpaqueToolkit2.merge(...opaqueToolkits);
1211
- const toolkitDefs = [
1212
- toolkitProp?.toolkit,
1213
- skillToolkit,
1214
- opaqueToolkit.toolkit
1215
- ].filter(isTruthy);
1216
- const mergedToolkit = Toolkit.merge(...toolkitDefs);
1217
- const combinedHandlerLayer = Layer2.mergeAll(Layer2.succeedContext(skillToolHandler), toolkitProp?.layer ?? OpaqueToolkit2.empty.layer, opaqueToolkit.layer);
1218
- return OpaqueToolkit2.make(mergedToolkit, combinedHandlerLayer);
1219
- });
1220
-
1221
- // src/session/AiContext.ts
1222
- var AiContext_exports = {};
1223
- __export(AiContext_exports, {
1224
- Binder: () => Binder,
1225
- Binding: () => Binding,
1226
- Bindings: () => Bindings
1227
- });
1228
- import { Atom, Registry as AtomRegistry } from "@effect-atom/atom-react";
1229
- import * as EArray from "effect/Array";
1230
- import * as Function3 from "effect/Function";
1231
- import * as Runtime from "effect/Runtime";
1232
- import * as Schema5 from "effect/Schema";
1233
- import { Skill } from "@dxos/compute";
1234
- import { Resource } from "@dxos/context";
1235
- import { Annotation, DXN as DXN2, Feed, Obj as Obj6, Query, Ref as Ref3, Type as Type2 } from "@dxos/echo";
1236
- import { assertArgument } from "@dxos/invariant";
1237
- import { EID as EID3 } from "@dxos/keys";
1238
- import { log as log4 } from "@dxos/log";
1239
- import { ComplexSet, isNonNullable as isNonNullable3 } from "@dxos/util";
1240
- var __dxlog_file5 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/AiContext.ts";
1241
- var Binding = class extends Type2.makeObject(DXN2.make("org.dxos.type.contextBinding", "0.1.0"))(Schema5.Struct({
1242
- skills: Schema5.Struct({
1243
- added: Schema5.Array(Ref3.Ref(Skill.Skill)),
1244
- removed: Schema5.Array(Ref3.Ref(Skill.Skill))
1245
- }),
1246
- objects: Schema5.Struct({
1247
- added: Schema5.Array(Ref3.Ref(Obj6.Unknown)),
1248
- removed: Schema5.Array(Ref3.Ref(Obj6.Unknown))
1249
- })
1250
- }).pipe(Annotation.HiddenAnnotation.set(true))) {
1251
- };
1252
- var Bindings = class {
1253
- skills = new ComplexSet((ref) => ref.uri);
1254
- // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.
1255
- objects = new ComplexSet((ref) => {
1256
- const echoUri = EID3.tryParse(ref.uri);
1257
- return echoUri ? EID3.getEntityId(echoUri) : void 0;
1258
- });
1259
- toJSON() {
1260
- return {
1261
- skills: EArray.fromIterable(this.skills).map((ref) => ref.uri),
1262
- objects: EArray.fromIterable(this.objects).map((ref) => ref.uri)
1263
- };
1264
- }
1265
- };
1266
- var Binder = class extends Resource {
1267
- _skills = Atom.make([]).pipe(Atom.keepAlive);
1268
- _objects = Atom.make([]).pipe(Atom.keepAlive);
1269
- _registry;
1270
- _feed;
1271
- _runtime;
1272
- #bindingsQuery;
1273
- constructor(options) {
1274
- super();
1275
- assertArgument(options.feed, "options.feed", "Feed is required");
1276
- assertArgument(options.runtime, "options.runtime", "Feed runtime is required");
1277
- this._feed = options.feed;
1278
- this._runtime = options.runtime;
1279
- this._registry = options.registry ?? AtomRegistry.make();
1280
- }
1281
- /**
1282
- * Returns the skills atom for subscription.
1283
- */
1284
- get skills() {
1285
- return this._skills;
1286
- }
1287
- /**
1288
- * Returns the objects atom for subscription.
1289
- */
1290
- get objects() {
1291
- return this._objects;
1292
- }
1293
- /**
1294
- * Gets the current skills value.
1295
- */
1296
- getSkills() {
1297
- return this._registry.get(this._skills);
1298
- }
1299
- /**
1300
- * Gets the current objects value.
1301
- */
1302
- getObjects() {
1303
- return this._registry.get(this._objects);
1304
- }
1305
- /**
1306
- * Subscribe to changes in skills.
1307
- */
1308
- subscribeSkills(cb) {
1309
- return this._registry.subscribe(this._skills, () => cb(this._registry.get(this._skills)));
1310
- }
1311
- /**
1312
- * Subscribe to changes in objects.
1313
- */
1314
- subscribeObjects(cb) {
1315
- return this._registry.subscribe(this._objects, () => cb(this._registry.get(this._objects)));
1316
- }
1317
- async _open() {
1318
- this.#bindingsQuery = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Query.type(Binding)));
1319
- const initialResults = await this.#bindingsQuery.run();
1320
- await this._updateBindings(initialResults);
1321
- this._ctx.onDispose(this.#bindingsQuery.subscribe(async () => {
1322
- await this._updateBindings(this.#bindingsQuery.results);
1323
- }));
1324
- }
1325
- /**
1326
- * Re-reads bindings from the feed to pick up changes made by other processes.
1327
- */
1328
- async sync() {
1329
- if (this.#bindingsQuery) {
1330
- const results = await this.#bindingsQuery.run();
1331
- log4("sync", {
1332
- bindingItems: results.length
1333
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 107, S: this });
1334
- await this._updateBindings(results);
1335
- log4("sync complete", {
1336
- skills: this._registry.get(this._skills).length,
1337
- skillKeys: this._registry.get(this._skills).map((bp) => Skill.getKey(bp))
1338
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 111, S: this });
1339
- }
1340
- }
1341
- async _updateBindings(items) {
1342
- if (items.length === 0) {
1343
- return;
1344
- }
1345
- const bindings = this._reduce(items);
1346
- log4("_updateBindings", {
1347
- items: items.length,
1348
- skillRefs: [
1349
- ...bindings.skills
1350
- ].map((ref) => ({
1351
- uri: ref.uri,
1352
- available: ref.isAvailable
1353
- }))
1354
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 123, S: this });
1355
- const currentSkills = this._registry.get(this._skills);
1356
- const currentObjects = this._registry.get(this._objects);
1357
- const resolvedSkills = await this._resolve(bindings.skills, currentSkills);
1358
- const resolvedObjects = await this._resolve(bindings.objects, currentObjects);
1359
- log4("_updateBindings resolved", {
1360
- resolvedSkills: resolvedSkills.length,
1361
- resolvedSkillKeys: resolvedSkills.map((bp) => Obj6.getMeta(bp).key ?? "<missing>")
1362
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 137, S: this });
1363
- const keyedSkills = resolvedSkills.filter((bp) => {
1364
- if (Obj6.getMeta(bp).key === void 0) {
1365
- log4.warn("dropping skill with no meta key", {
1366
- uri: Obj6.getURI(bp)
1367
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 145, S: this });
1368
- return false;
1369
- }
1370
- return true;
1371
- });
1372
- const reducedSkillDxns = new Set([
1373
- ...bindings.skills
1374
- ].map((ref) => ref.uri));
1375
- const reducedObjectDxns = new Set([
1376
- ...bindings.objects
1377
- ].map((ref) => ref.uri));
1378
- const filteredSkills = currentSkills.filter((obj) => {
1379
- const uri = Obj6.getURI(obj);
1380
- return uri != null && reducedSkillDxns.has(uri) && Obj6.getMeta(obj).key !== void 0;
1381
- });
1382
- const filteredObjects = currentObjects.filter((obj) => {
1383
- const uri = Obj6.getURI(obj);
1384
- return uri != null && reducedObjectDxns.has(uri);
1385
- });
1386
- const mergedSkills = this._mergeInto(filteredSkills, keyedSkills);
1387
- const mergedObjects = this._mergeInto(filteredObjects, resolvedObjects);
1388
- this._registry.set(this._skills, mergedSkills);
1389
- this._registry.set(this._objects, mergedObjects);
1390
- log4("updated bindings", {
1391
- skills: mergedSkills.length,
1392
- objects: mergedObjects.length
1393
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 172, S: this });
1394
- }
1395
- async _close() {
1396
- this._registry.set(this._skills, []);
1397
- this._registry.set(this._objects, []);
1398
- }
1399
- async bind({ skills, objects }) {
1400
- const currentSkills = this._registry.get(this._skills);
1401
- const currentObjects = this._registry.get(this._objects);
1402
- const { added: addedSkills, next: nextSkills } = this._processBindings(skills, currentSkills);
1403
- const { added: addedObjects, next: nextObjects } = this._processBindings(objects, currentObjects);
1404
- if (!addedSkills.length && !addedObjects.length) {
1405
- return;
1406
- }
1407
- this._registry.set(this._skills, nextSkills);
1408
- this._registry.set(this._objects, nextObjects);
1409
- log4("bind", {
1410
- skills: addedSkills.length,
1411
- objects: addedObjects.length
1412
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 193, S: this });
1413
- await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
1414
- Obj6.make(Binding, {
1415
- skills: {
1416
- added: addedSkills,
1417
- removed: []
1418
- },
1419
- objects: {
1420
- added: addedObjects,
1421
- removed: []
1422
- }
1423
- })
1424
- ]));
1425
- }
1426
- async unbind({ skills, objects }) {
1427
- if (!skills?.length && !objects?.length) {
1428
- return;
1429
- }
1430
- const removedSkillDxns = (skills ?? []).map((ref) => ref.uri);
1431
- const removedObjectDxns = (objects ?? []).map((ref) => ref.uri);
1432
- if (removedSkillDxns.length > 0) {
1433
- const current = this._registry.get(this._skills);
1434
- this._registry.set(this._skills, current.filter((obj) => !removedSkillDxns.some((uri) => Obj6.getURI(obj) === uri)));
1435
- }
1436
- if (removedObjectDxns.length > 0) {
1437
- const current = this._registry.get(this._objects);
1438
- this._registry.set(this._objects, current.filter((obj) => !removedObjectDxns.some((uri) => Obj6.getURI(obj) === uri)));
1439
- }
1440
- log4("unbind", {
1441
- skills: skills?.length,
1442
- objects: objects?.length
1443
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 225, S: this });
1444
- await Runtime.runPromise(this._runtime)(Feed.append(this._feed, [
1445
- Obj6.make(Binding, {
1446
- skills: {
1447
- added: [],
1448
- removed: skills ?? []
1449
- },
1450
- objects: {
1451
- added: [],
1452
- removed: objects ?? []
1453
- }
1454
- })
1455
- ]));
1456
- }
1457
- /**
1458
- * Process bindings to filter duplicates and determine next state.
1459
- */
1460
- _processBindings(refs, current) {
1461
- const next = [
1462
- ...current
1463
- ];
1464
- const added = [];
1465
- if (!refs?.length) {
1466
- return {
1467
- added,
1468
- next
1469
- };
1470
- }
1471
- const seen = new Set(current.map((obj) => Obj6.getURI(obj)));
1472
- for (const ref of refs) {
1473
- const uri = ref.uri;
1474
- if (seen.has(uri)) {
1475
- continue;
1476
- }
1477
- seen.add(uri);
1478
- added.push(ref);
1479
- if (ref.isAvailable) {
1480
- const target = ref.target;
1481
- if (target) {
1482
- next.push(target);
1483
- }
1484
- }
1485
- }
1486
- return {
1487
- added,
1488
- next
1489
- };
1490
- }
1491
- /**
1492
- * Reduce results into sets of skills and objects.
1493
- */
1494
- _reduce(items) {
1495
- return Function3.pipe(items, EArray.reduce(new Bindings(), (context, { skills, objects }) => {
1496
- skills.added.forEach((ref) => context.skills.add(ref));
1497
- skills.removed.forEach((ref) => context.skills.delete(ref));
1498
- objects.added.forEach((ref) => context.objects.add(ref));
1499
- objects.removed.forEach((ref) => {
1500
- for (const obj of context.objects) {
1501
- if (obj.uri === ref.uri || EID3.tryParse(obj.uri) && EID3.tryParse(ref.uri) && EID3.getEntityId(EID3.tryParse(obj.uri)) === EID3.getEntityId(EID3.tryParse(ref.uri))) {
1502
- context.objects.delete(obj);
1503
- }
1504
- }
1505
- });
1506
- return context;
1507
- }));
1508
- }
1509
- /**
1510
- * Merge resolved items into the current set, adding only items not already present (by DXN).
1511
- */
1512
- _mergeInto(current, resolved) {
1513
- const seen = new Set(current.map((obj) => Obj6.getURI(obj)));
1514
- const merged = [
1515
- ...current
1516
- ];
1517
- for (const obj of resolved) {
1518
- const uri = Obj6.getURI(obj);
1519
- if (!seen.has(uri)) {
1520
- seen.add(uri);
1521
- merged.push(obj);
1522
- }
1523
- }
1524
- return merged;
1525
- }
1526
- /**
1527
- * Resolve references to objects, loading them first if needed and falling back to existing objects.
1528
- * DXN refs (e.g. `dxn:org.dxos.skill.database`) resolve via the wired-up ECHO ref resolver
1529
- * which already spans both the space DB and the hypergraph registry.
1530
- */
1531
- async _resolve(refs, current) {
1532
- const refArray = [
1533
- ...refs
1534
- ];
1535
- await Promise.all(refArray.map((ref) => ref.tryLoad()));
1536
- return refArray.map((ref) => {
1537
- let target;
1538
- if (ref.isAvailable) {
1539
- target = ref.target;
1540
- }
1541
- return target ?? current.find((obj) => Obj6.getURI(obj) === ref.uri);
1542
- }).filter(isNonNullable3);
1543
- }
1544
- };
1545
-
1546
- // src/session/AiSession.ts
1547
- var AiSession_exports = {};
1548
- __export(AiSession_exports, {
1549
- Session: () => Session
1550
- });
1551
- import * as Array4 from "effect/Array";
1552
- import * as Effect10 from "effect/Effect";
1553
- import * as Either from "effect/Either";
1554
- import { pipe as pipe4 } from "effect/Function";
1555
- import * as Layer4 from "effect/Layer";
1556
- import * as Record2 from "effect/Record";
1557
- import * as Runtime2 from "effect/Runtime";
1558
- import { Operation as Operation3, Trace as Trace3 } from "@dxos/compute";
1559
- import { Resource as Resource2 } from "@dxos/context";
1560
- import { Feed as Feed5, Filter as Filter4, Obj as Obj10 } from "@dxos/echo";
1561
- import { invariant as invariant3 } from "@dxos/invariant";
1562
- import { log as log6 } from "@dxos/log";
1563
- import { McpToolkit } from "@dxos/mcp-client";
1564
- import { Message as Message6 } from "@dxos/types";
1565
-
1566
- // src/session/Harness.ts
1567
- var Harness_exports = {};
1568
- __export(Harness_exports, {
1569
- HarnessService: () => HarnessService,
1570
- NotSupportedError: () => NotSupportedError,
1571
- bindContext: () => bindContext,
1572
- binder: () => binder,
1573
- enqueueMessage: () => enqueueMessage,
1574
- fromBinder: () => fromBinder,
1575
- history: () => history,
1576
- layerSpec: () => layerSpec,
1577
- make: () => make3,
1578
- queryContext: () => queryContext,
1579
- setAlarm: () => setAlarm
1580
- });
1581
- import * as Context3 from "effect/Context";
1582
- import * as DateTime from "effect/DateTime";
1583
- import * as Effect8 from "effect/Effect";
1584
- import * as Layer3 from "effect/Layer";
1585
- import * as Option4 from "effect/Option";
1586
- import { LayerSpec, Process, ServiceNotAvailableError } from "@dxos/compute";
1587
- import { ProcessManager } from "@dxos/compute-runtime";
1588
- import { Annotation as Annotation2, Database as Database2, EID as EID4, Feed as Feed4, Filter as Filter3 } from "@dxos/echo";
1589
- import { EffectEx } from "@dxos/effect";
1590
- import { BaseError as BaseError2 } from "@dxos/errors";
1591
- import { Message as Message5 } from "@dxos/types";
1592
-
1593
- // src/session/SessionLoader.ts
1594
- import * as Effect7 from "effect/Effect";
1595
- import { Feed as Feed3, Filter as Filter2, Obj as Obj8 } from "@dxos/echo";
1596
- import { Message as Message4 } from "@dxos/types";
1597
-
1598
- // src/session/SessionLink.ts
1599
- var SessionLink_exports = {};
1600
- __export(SessionLink_exports, {
1601
- SessionLink: () => SessionLink
1602
- });
1603
- import * as Schema6 from "effect/Schema";
1604
- import { DXN as DXN3, Feed as Feed2, Obj as Obj7, Ref as Ref4, Type as Type3 } from "@dxos/echo";
1605
- var SessionLink = class extends Type3.makeObject(DXN3.make("org.dxos.type.sessionLink", "0.1.0"))(Schema6.Struct({
1606
- /** Reference to the feed of the source session. */
1607
- feedRef: Ref4.Ref(Feed2.Feed),
1608
- /** Messages from the source feed up to and including this message ID are injected. */
1609
- messageId: Obj7.ID
1610
- })) {
1611
- };
1612
-
1613
- // src/session/SessionLoader.ts
1614
- var SessionLoader = class {
1615
- /**
1616
- * Prepends linked history to `messages` when the feed contains a SessionLink.
1617
- * Queries the feed for any SessionLink record; if found, loads messages from
1618
- * the referenced feed up to and including `messageId` and prepends them.
1619
- */
1620
- reifyHistory(feed, messages) {
1621
- return Effect7.gen(function* () {
1622
- const links = yield* Feed3.query(feed, Filter2.type(SessionLink)).run;
1623
- const sessionLinks = links.filter(Obj8.instanceOf(SessionLink));
1624
- const link = sessionLinks[0];
1625
- if (!link) {
1626
- return messages;
1627
- }
1628
- const sourceFeed = link.feedRef.target;
1629
- if (!sourceFeed) {
1630
- return messages;
1631
- }
1632
- const sourceMessages = yield* Feed3.query(sourceFeed, Filter2.type(Message4.Message)).run;
1633
- const filtered = sourceMessages.filter(Obj8.instanceOf(Message4.Message));
1634
- const sorted = [
1635
- ...filtered
1636
- ].sort((a, b) => a.created.localeCompare(b.created));
1637
- const cutoffIndex = sorted.findIndex((m) => m.id === link.messageId);
1638
- if (cutoffIndex < 0) {
1639
- return messages;
1640
- }
1641
- return [
1642
- ...sorted.slice(0, cutoffIndex + 1),
1643
- ...messages
1644
- ];
1645
- });
1646
- }
1647
- };
1648
-
1649
- // src/session/Harness.ts
1650
- var HarnessService = class extends Context3.Tag("@dxos/assistant/HarnessService")() {
1651
- };
1652
- var binder = Effect8.flatMap(HarnessService, (service) => service.binder);
1653
- var queryContext = (filter2) => Effect8.flatMap(HarnessService, (service) => service.queryContext(filter2));
1654
- var history = Effect8.flatMap(HarnessService, (service) => service.history);
1655
- var enqueueMessage = (options) => Effect8.flatMap(HarnessService, (service) => service.enqueueMessage(options));
1656
- var setAlarm = (options) => Effect8.flatMap(HarnessService, (service) => service.setAlarm(options));
1657
- var bindContext = ({ skills, objects }) => Effect8.gen(function* () {
1658
- const sessionBinder = yield* binder;
1659
- yield* Effect8.promise(() => sessionBinder.bind({
1660
- skills,
1661
- objects
1662
- }));
1663
- });
1664
- var NotSupportedError = class extends BaseError2.extend("NotSupportedError", "Operation not supported") {
1665
- };
1666
- var layerSpec = LayerSpec.make({
1667
- affinity: "process",
1668
- requires: [
1669
- Database2.Service,
1670
- ProcessManager.Service
1671
- ],
1672
- provides: [
1673
- HarnessService
1674
- ]
1675
- }, (context) => Layer3.scoped(HarnessService, Effect8.gen(function* () {
1676
- if (!context.conversation) {
1677
- return yield* Effect8.die(new ServiceNotAvailableError(HarnessService.key, {
1678
- message: `Service not available: ${HarnessService.key} \u2014 process spawn is missing 'conversation' in environment (set via Operation.withInvocationOptions or ProcessManager.spawn environment)`
1679
- }));
1680
- }
1681
- const conversation = context.conversation;
1682
- const processManager = yield* ProcessManager.Service;
1683
- const runtime2 = yield* Effect8.runtime();
1684
- return yield* make3({
1685
- conversation,
1686
- processManager,
1687
- runtime: runtime2
1688
- });
1689
- })));
1690
- var make3 = ({ conversation, processManager, runtime: runtime2 }) => Effect8.gen(function* () {
1691
- const feed = yield* Database2.resolve(EID4.parse(conversation), Feed4.Feed).pipe(Effect8.provide(runtime2), Effect8.orDie);
1692
- const boundBinder = yield* EffectEx.acquireReleaseResource(() => new Binder({
1693
- feed,
1694
- runtime: runtime2
1695
- }));
1696
- return makeService({
1697
- feed,
1698
- runtime: runtime2,
1699
- binder: boundBinder,
1700
- owningHost: lookupOwningHost(processManager, conversation)
1701
- });
1702
- });
1703
- var fromBinder = ({ feed, runtime: runtime2, binder: binder2 }) => makeService({
1704
- feed,
1705
- runtime: runtime2,
1706
- binder: binder2,
1707
- owningHost: Effect8.fail(new NotSupportedError())
1708
- });
1709
- var makeService = ({ feed, runtime: runtime2, binder: binder2, owningHost }) => ({
1710
- binder: Effect8.succeed(binder2),
1711
- history: Effect8.gen(function* () {
1712
- const messages = yield* Feed4.query(feed, Filter3.type(Message5.Message)).run;
1713
- return yield* new SessionLoader().reifyHistory(feed, messages);
1714
- }).pipe(Effect8.provide(runtime2)),
1715
- queryContext: (filter2) => Effect8.sync(() => {
1716
- const match = Filter3.toPredicate(filter2);
1717
- return binder2.getObjects().filter(match);
1718
- }),
1719
- enqueueMessage: ({ content }) => owningHost.pipe(Effect8.flatMap((rpc) => rpc.enqueueMessage({
1720
- content
1721
- }))),
1722
- setAlarm: ({ at, message }) => owningHost.pipe(Effect8.flatMap((rpc) => rpc.setAlarm({
1723
- at: DateTime.toUtc(at),
1724
- message
1725
- })))
1726
- });
1727
- var lookupOwningHost = (processManager, conversation) => Effect8.gen(function* () {
1728
- const processes = yield* processManager.list({
1729
- target: conversation
1730
- });
1731
- const host = processes.find((process) => !isTerminalProcess(process.status.state) && Option4.getOrElse(Annotation2.getDictionary(process.params.annotations, Process.HarnessHostAnnotation), () => false));
1732
- if (!host) {
1733
- return yield* Effect8.fail(new NotSupportedError());
1734
- }
1735
- return host.rpc;
1736
- });
1737
- var isTerminalProcess = (state) => state === Process.State.SUCCEEDED || state === Process.State.FAILED || state === Process.State.TERMINATED;
1738
-
1739
- // src/session/SkillHooks.ts
1740
- var SkillHooks_exports = {};
1741
- __export(SkillHooks_exports, {
1742
- runHooks: () => runHooks
1743
- });
1744
- import * as Effect9 from "effect/Effect";
1745
- import { Operation as Operation2, Skill as Skill2 } from "@dxos/compute";
1746
- import { Database as Database3, Obj as Obj9 } from "@dxos/echo";
1747
- import { invariant as invariant2 } from "@dxos/invariant";
1748
- import { log as log5 } from "@dxos/log";
1749
- var __dxlog_file6 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/SkillHooks.ts";
1750
- var runHooks = ({ skills, phase, invoke }) => Effect9.gen(function* () {
1751
- for (const skill of skills) {
1752
- for (const hook of skill.hooks ?? []) {
1753
- if (hook.spec._tag !== phase) {
1754
- continue;
1755
- }
1756
- if (!hook.function) {
1757
- continue;
1758
- }
1759
- yield* Effect9.gen(function* () {
1760
- const record = yield* Database3.load(hook.function);
1761
- invariant2(Obj9.instanceOf(Operation2.PersistentOperation, record), "Hook function must be an operation.", { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 28, S: this, A: ["Obj.instanceOf(Operation.PersistentOperation, record)", "'Hook function must be an operation.'"] });
1762
- const operation = Operation2.deserialize(record);
1763
- yield* invoke(operation, {
1764
- ...hook.input
1765
- });
1766
- }).pipe(Effect9.catchAllCause((cause) => Effect9.sync(() => log5.warn("skill hook failed", {
1767
- phase,
1768
- skill: Skill2.getKey(skill),
1769
- cause
1770
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 35, S: this }))));
1771
- }
1772
- }
1773
- });
1774
-
1775
- // src/session/AiSession.ts
1776
- var __dxlog_file7 = "/__w/dxos/dxos/packages/core/compute/assistant/src/session/AiSession.ts";
1777
- var SUMMARY_THRESHOLD = 8e4;
1778
- var Session = class extends Resource2 {
1779
- /**
1780
- * Skills and objects bound to the session.
1781
- */
1782
- _binder;
1783
- _feed;
1784
- _runtime;
1785
- _sessionLoader = new SessionLoader();
1786
- constructor(options) {
1787
- super();
1788
- this._feed = options.feed;
1789
- this._runtime = options.runtime;
1790
- invariant3(this._feed, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 45, S: this, A: ["this._feed", ""] });
1791
- invariant3(this._runtime, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 46, S: this, A: ["this._runtime", ""] });
1792
- this._binder = new Binder({
1793
- feed: this._feed,
1794
- runtime: this._runtime,
1795
- registry: options.registry
1796
- });
1797
- }
1798
- async _open() {
1799
- await this._binder.open(this._ctx);
1800
- }
1801
- get feed() {
1802
- return this._feed;
1803
- }
1804
- get context() {
1805
- return this._binder;
1806
- }
1807
- async getHistory() {
1808
- const queryResult = await Runtime2.runPromise(this._runtime)(Feed5.query(this._feed, Filter4.type(Message6.Message)));
1809
- const items = await queryResult.run();
1810
- const messages = items.filter(Obj10.instanceOf(Message6.Message));
1811
- return Runtime2.runPromise(this._runtime)(this._sessionLoader.reifyHistory(this._feed, messages));
1812
- }
1813
- getTools() {
1814
- return Effect10.gen(this, function* () {
1815
- const toolkit = yield* createToolkit({
1816
- skills: this.context.getSkills()
1817
- });
1818
- return toolkit.toolkit.tools;
1819
- }).pipe(Effect10.orDie);
1820
- }
1821
- /**
1822
- * Not provided by default, since users might want to override them.
1823
- */
1824
- makeToolExecutionServices() {
1825
- return ToolExecutionServices.pipe(Layer4.provide(Operation3.withInvocationOptions({
1826
- conversation: Obj10.getURI(this._feed)
1827
- })));
1828
- }
1829
- /**
1830
- * Creates a new cancelable request effect.
1831
- */
1832
- createRequest(params) {
1833
- return Effect10.gen(this, function* () {
1834
- const history2 = yield* Effect10.promise(() => this.getHistory());
1835
- const skills = this.context.getSkills();
1836
- const objects = this.context.getObjects();
1837
- log6("run", {
1838
- history: history2.length,
1839
- skills: skills.length,
1840
- objects: objects.length
1841
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 90, S: this });
1842
- const request = new AiRequest_exports.Request({
1843
- summarizationThreshold: SUMMARY_THRESHOLD,
1844
- observer: params.observer,
1845
- persist: params.persist,
1846
- onOutput: (message) => Effect10.promise(() => Runtime2.runPromise(this._runtime)(Feed5.append(this._feed, [
1847
- message
1848
- ])))
1849
- });
1850
- yield* request.begin({
1851
- history: history2,
1852
- skills,
1853
- objects,
1854
- prompt: params.prompt,
1855
- system: params.system
1856
- });
1857
- yield* runHooks({
1858
- skills,
1859
- phase: "begin-request",
1860
- invoke: (operation, input) => Operation3.invoke(operation, input).pipe(Effect10.asVoid, Effect10.orDie)
1861
- });
1862
- do {
1863
- yield* Effect10.promise(() => this.context.sync());
1864
- const currentSkills = this.context.getSkills();
1865
- const mcps = yield* connectMcpServers(currentSkills, params.mcpServers);
1866
- const toolkit = yield* createToolkit({
1867
- toolkit: params.toolkit,
1868
- skills: currentSkills,
1869
- opaqueToolkits: mcps
1870
- });
1871
- log6("toolkit", {
1872
- tools: Record2.keys(toolkit.toolkit.tools)
1873
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 127, S: this });
1874
- const system = yield* formatSystemPrompt({
1875
- system: params.system,
1876
- skills: currentSkills,
1877
- objects: this.context.getObjects()
1878
- }).pipe(Effect10.orDie);
1879
- const { done, finishReason } = yield* request.runAgentTurn({
1880
- system,
1881
- toolkit
1882
- });
1883
- if (done) {
1884
- break;
1885
- }
1886
- if (finishReason === "pause") {
1887
- continue;
1888
- }
1889
- yield* request.runTools({
1890
- toolkit
1891
- });
1892
- } while (true);
1893
- log6("result", {
1894
- messages: request.pending.length,
1895
- duration: request.duration,
1896
- toolCalls: request.toolCalls
1897
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 151, S: this });
1898
- return [
1899
- ...request.pending
1900
- ];
1901
- }).pipe(Effect10.provide(Layer4.mergeAll(
1902
- // Tier A only: the agent's own turn fiber has no `ProcessManager.Service` in scope, so
1903
- // Tier B (setAlarm/enqueueMessage) is reachable only by child operations through the
1904
- // process-affinity HarnessService LayerSpec — not from here.
1905
- Layer4.succeed(HarnessService, fromBinder({
1906
- feed: this._feed,
1907
- runtime: this._runtime,
1908
- binder: this.context
1909
- })),
1910
- Operation3.withInvocationOptions({
1911
- conversation: Obj10.getURI(this._feed)
1912
- })
1913
- )), Effect10.withSpan("AiSession.createRequest"));
1914
- }
1915
- };
1916
- var connectMcpServers = (skills, spaceMcpServers = []) => {
1917
- const skillServers = pipe4(skills, Array4.flatMap((_) => _.mcpServers ?? []), Array4.map(({ url, protocol, apiKey }) => ({
1918
- url,
1919
- protocol,
1920
- apiKey
1921
- })));
1922
- const spaceServers = spaceMcpServers.map(({ url, protocol, apiKey }) => ({
1923
- url,
1924
- protocol,
1925
- apiKey
1926
- }));
1927
- const allServers = [
1928
- ...skillServers,
1929
- ...spaceServers
1930
- ];
1931
- return pipe4(allServers, Effect10.forEach((options) => McpToolkit.make(options).pipe(
1932
- // NOTE: Type-inference fails here without explicit void return.
1933
- Effect10.tap((toolkit) => log6.info("Connected to MCP server", {
1934
- url: options.url,
1935
- tools: Object.keys(toolkit.toolkit.tools).length
1936
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 187, S: void 0 })),
1937
- // Surface typed connection failures via ephemeral trace + warn log, then drop the server.
1938
- Effect10.tapError((error) => Effect10.gen(function* () {
1939
- log6.warn("Failed to connect to MCP server", {
1940
- url: error.url,
1941
- protocol: error.protocol,
1942
- message: error.message
1943
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 192, S: this });
1944
- yield* Trace3.write(McpServerError, {
1945
- url: error.url,
1946
- protocol: error.protocol,
1947
- message: error.message
1948
- });
1949
- })),
1950
- // Catch unexpected defects too (e.g. malformed tool schemas) so a single broken
1951
- // server can never abort the whole turn — surface them through the same channel.
1952
- Effect10.catchAllDefect((defect) => Effect10.gen(function* () {
1953
- const message = defect instanceof Error ? defect.message : String(defect);
1954
- log6.warn("Unexpected MCP defect", {
1955
- url: options.url,
1956
- message
1957
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 206, S: this });
1958
- yield* Trace3.write(McpServerError, {
1959
- url: options.url,
1960
- protocol: options.protocol,
1961
- message: `Unexpected MCP failure: ${message}`
1962
- });
1963
- return yield* Effect10.fail(new McpToolkit.McpConnectionError({
1964
- url: options.url,
1965
- protocol: options.protocol,
1966
- message
1967
- }));
1968
- })),
1969
- Effect10.either
1970
- )), Effect10.map(Array4.filterMap((_) => Either.getRight(_))));
1971
- };
1972
-
1973
- // src/session/harness-control.ts
1974
- import * as Rpc from "@effect/rpc/Rpc";
1975
- import * as RpcGroup from "@effect/rpc/RpcGroup";
1976
- import * as Schema7 from "effect/Schema";
1977
- import { ContentBlock as ContentBlock4 } from "@dxos/types";
1978
- var HarnessControl = RpcGroup.make(Rpc.make("setAlarm", {
1979
- payload: Schema7.Struct({
1980
- at: Schema7.DateTimeUtc,
1981
- message: Schema7.NullOr(Schema7.String)
1982
- }),
1983
- success: Schema7.Void
1984
- }), Rpc.make("enqueueMessage", {
1985
- payload: Schema7.Struct({
1986
- content: Schema7.Array(ContentBlock4.Any)
1987
- }),
1988
- success: Schema7.Void
1989
- }));
1990
-
1991
- // src/templates/system.ts
1992
- import defaultsDeep from "lodash.defaultsdeep";
1993
- import { Template as Template2 } from "@dxos/compute";
1994
-
1995
- // raw-loader:/__w/dxos/dxos/packages/core/compute/assistant/src/templates/instructions/format.tpl
1996
- var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Skills\n\nYou may be provided with Skill definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <skill> 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";
1997
-
1998
- // raw-loader:/__w/dxos/dxos/packages/core/compute/assistant/src/templates/instructions/system.tpl
1999
- 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 skill definitions?\n- If you can't complete the task using the available skill definitions, query the list of available skill definitions using the appropriate tool.\n- Identify which skill 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 skill definitions already available?\n- If not, select which skill 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## Skills 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. Navigation is always two steps: first resolve a navigation path with Resolve navigation targets, then open that path with Open.\n- The Open tool accepts navigation **paths** only. Never pass an object DXN, URI, or id to Open \u2014 pass only a `path` returned by Resolve navigation targets. Passing anything else will fail to navigate.\n- To open a specific object: call Resolve navigation targets with the object's URI in the `query.uri` field \u2014 use the value from the object's `<dxn>` tag in context (which may be an `echo:` EID or a `dxn:` DXN), then pass the returned target's `path` to Open.\n- To navigate to a page (not a specific object): call Resolve navigation targets without arguments to list the available pages, then pass the chosen target's `path` to Open.\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>";
2000
-
2001
- // src/templates/system.ts
2002
- var createSystemPrompt = (options = {}) => Template2.process(format_default, defaultsDeep(options, {
2003
- DATETIME: (/* @__PURE__ */ new Date()).toISOString()
2004
- }));
2005
- var SYSTEM_ID = "01K2J2FZWH39F55CS7B26GP1Q3";
2006
- var templates = {
2007
- system: Template2.make({
2008
- id: SYSTEM_ID,
2009
- source: system_default
2010
- })
2011
- };
2012
- export {
2013
- AgentRequestBegin,
2014
- AgentRequestEnd,
2015
- AiAssistantError,
2016
- AiContext_exports as AiContext,
2017
- AiModelError,
2018
- AiRequest_exports as AiRequest,
2019
- AiSession_exports as AiSession,
2020
- CompleteBlock,
2021
- ExecutionGraph,
2022
- GenerationObserver,
2023
- Harness_exports as Harness,
2024
- HarnessControl,
2025
- McpServerError,
2026
- PartialBlock,
2027
- RefFromLLM,
2028
- SessionLink_exports as SessionLink,
2029
- SessionLoader,
2030
- SkillHooks_exports as SkillHooks,
2031
- ToolExecutionServices,
2032
- applyDiffs,
2033
- computeDiffsWithCursors,
2034
- createArtifactElement,
2035
- createSystemPrompt,
2036
- createToolkit,
2037
- formatSystemPrompt,
2038
- formatUserPrompt,
2039
- getOperationFromTool,
2040
- makeToolExecutionService,
2041
- makeToolExecutionServiceFromOperationInvoker,
2042
- makeToolResolverFromOperations,
2043
- mapAiError,
2044
- reduceDiffs,
2045
- templates
2046
- };
2047
- //# sourceMappingURL=index.mjs.map