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