@dxos/assistant 0.8.4-main.dedc0f3 → 0.8.4-main.e098934

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/assistant",
3
- "version": "0.8.4-main.dedc0f3",
3
+ "version": "0.8.4-main.e098934",
4
4
  "description": "Natural language interface to DXOS",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -48,26 +48,26 @@
48
48
  "chalk": "^4.1.0",
49
49
  "handlebars": "4.7.8",
50
50
  "lodash.defaultsdeep": "^4.6.1",
51
- "@dxos/ai": "0.8.4-main.dedc0f3",
52
- "@dxos/blueprints": "0.8.4-main.dedc0f3",
53
- "@dxos/context": "0.8.4-main.dedc0f3",
54
- "@dxos/async": "0.8.4-main.dedc0f3",
55
- "@dxos/debug": "0.8.4-main.dedc0f3",
56
- "@dxos/echo-db": "0.8.4-main.dedc0f3",
57
- "@dxos/echo-protocol": "0.8.4-main.dedc0f3",
58
- "@dxos/echo-schema": "0.8.4-main.dedc0f3",
59
- "@dxos/errors": "0.8.4-main.dedc0f3",
60
- "@dxos/functions": "0.8.4-main.dedc0f3",
61
- "@dxos/effect": "0.8.4-main.dedc0f3",
62
- "@dxos/graph": "0.8.4-main.dedc0f3",
63
- "@dxos/keys": "0.8.4-main.dedc0f3",
64
- "@dxos/echo": "0.8.4-main.dedc0f3",
65
- "@dxos/log": "0.8.4-main.dedc0f3",
66
- "@dxos/node-std": "0.8.4-main.dedc0f3",
67
- "@dxos/schema": "0.8.4-main.dedc0f3",
68
- "@dxos/invariant": "0.8.4-main.dedc0f3",
69
- "@dxos/util": "0.8.4-main.dedc0f3",
70
- "@dxos/live-object": "0.8.4-main.dedc0f3"
51
+ "@dxos/ai": "0.8.4-main.e098934",
52
+ "@dxos/blueprints": "0.8.4-main.e098934",
53
+ "@dxos/async": "0.8.4-main.e098934",
54
+ "@dxos/context": "0.8.4-main.e098934",
55
+ "@dxos/debug": "0.8.4-main.e098934",
56
+ "@dxos/echo": "0.8.4-main.e098934",
57
+ "@dxos/echo-db": "0.8.4-main.e098934",
58
+ "@dxos/echo-protocol": "0.8.4-main.e098934",
59
+ "@dxos/effect": "0.8.4-main.e098934",
60
+ "@dxos/functions": "0.8.4-main.e098934",
61
+ "@dxos/errors": "0.8.4-main.e098934",
62
+ "@dxos/echo-schema": "0.8.4-main.e098934",
63
+ "@dxos/graph": "0.8.4-main.e098934",
64
+ "@dxos/invariant": "0.8.4-main.e098934",
65
+ "@dxos/keys": "0.8.4-main.e098934",
66
+ "@dxos/log": "0.8.4-main.e098934",
67
+ "@dxos/node-std": "0.8.4-main.e098934",
68
+ "@dxos/live-object": "0.8.4-main.e098934",
69
+ "@dxos/schema": "0.8.4-main.e098934",
70
+ "@dxos/util": "0.8.4-main.e098934"
71
71
  },
72
72
  "devDependencies": {
73
73
  "@types/lodash.defaultsdeep": "^4.6.6",
package/src/errors.ts CHANGED
@@ -5,11 +5,11 @@
5
5
  import { BaseError } from '@dxos/errors';
6
6
 
7
7
  /**
8
- * Generic error for AI agent execution.
8
+ * Generic error from AI model.
9
9
  */
10
- export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR') {}
10
+ export class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}
11
11
 
12
12
  /**
13
- * Parsed error from the anthropic API.
13
+ * Generic error for AI agent execution.
14
14
  */
15
- export class AnthropicError extends BaseError.extend('ANTHROPIC_ERROR') {}
15
+ export class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant error') {}
@@ -13,7 +13,7 @@ describe('insertReferences', () => {
13
13
  };
14
14
 
15
15
  expect(insertReferences('This is a computational irreducibility test.', quotes)).toBe(
16
- 'This is a [computational irreducibility][dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1] test.',
16
+ 'This is a [computational irreducibility](dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1) test.',
17
17
  );
18
18
  expect(
19
19
  insertReferences(
@@ -21,7 +21,7 @@ describe('insertReferences', () => {
21
21
  quotes,
22
22
  ),
23
23
  ).toBe(
24
- "And what I'd like to talk today about is Steven Wolfram's concept of a [computational irreducibility][dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1].",
24
+ "And what I'd like to talk today about is Steven Wolfram's concept of a [computational irreducibility](dxn:echo:@:01JTG9JW11XGWJZ32AW8ET93D1).",
25
25
  );
26
26
  });
27
27
  });
@@ -51,7 +51,7 @@ export const insertReferences = (text: string, quotes: ReferencedQuotes) => {
51
51
 
52
52
  // Use a case-insensitive regular expression to replace the quote.
53
53
  const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
54
- text = text.replace(regex, `[${quote.quote}][${DXN.fromLocalObjectId(quote.id).toString()}]`);
54
+ text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);
55
55
  }
56
56
 
57
57
  return text;
@@ -6,7 +6,7 @@ import { AiError } from '@effect/ai';
6
6
  import { HttpClientError } from '@effect/platform';
7
7
  import { Effect, Schema } from 'effect';
8
8
 
9
- import { AnthropicError } from '../errors';
9
+ import { AiModelError } from '../errors';
10
10
 
11
11
  const AnthropicErrorResponse = Schema.Struct({
12
12
  type: Schema.Literal('error'),
@@ -24,7 +24,10 @@ export const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError>
24
24
  Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),
25
25
  );
26
26
 
27
- const parsedCause = new AnthropicError(`${body.error.type}: ${body.error.message}`);
27
+ const parsedCause = new AiModelError({
28
+ message: body.error.message,
29
+ context: { model: 'anthropic', type: body.error.type },
30
+ });
28
31
  return new AiError.AiError({
29
32
  description: body.error.message,
30
33
  module: err.module,
@@ -84,7 +84,7 @@ export const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunPara
84
84
  artifactDiffResolver.value.resolve(
85
85
  [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
86
86
  ),
87
- catch: AiAssistantError.wrap('Artifact diff resolution error'),
87
+ catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),
88
88
  });
89
89
 
90
90
  log('version', { artifactDiff, versions });
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/session/artifact-diff.ts", "../../../src/session/observer.ts", "../../../src/errors.ts", "../../../src/session/session.ts", "../../../src/session/error-handling.ts", "../../../src/session/format.ts", "../../../src/session/toolkit.ts", "../../../src/session/version-pin.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n *\n * Can be optionally provided to the session run call.\n */\n// TODO(dmaretskyi): Convert to Context.Reference\nexport class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<\n ArtifactDiffResolver,\n ArtifactDiffResolver.Service\n>() {}\n\nexport namespace ArtifactDiffResolver {\n export type Service = {\n resolve: (\n artifacts: {\n id: ObjectId;\n lastVersion: ObjectVersion;\n }[],\n ) => Promise<\n Map<\n ObjectId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n >;\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Function } from 'effect';\n\nimport { type AiParser, type ConsolePrinter } from '@dxos/ai';\nimport { type DataType } from '@dxos/schema';\n\n/**\n * Live observer of the generation process.\n */\nexport interface GenerationObserver extends AiParser.ParseResponseCallbacks {\n /**\n * Complete messages fired during the session, both from the model and from the user.\n * This message will contain all message blocks emitted through the `onBlock` callback.\n */\n onMessage: (message: DataType.Message) => Effect.Effect<void>;\n}\n\nexport const GenerationObserver = Object.freeze({\n make: ({\n onBegin = Function.constant(Effect.void),\n onPart = Function.constant(Effect.void),\n onBlock = Function.constant(Effect.void),\n onEnd = Function.constant(Effect.void),\n onMessage = Function.constant(Effect.void),\n }: Partial<GenerationObserver> = {}): GenerationObserver => ({\n onBegin,\n onPart,\n onBlock,\n onEnd,\n onMessage,\n }),\n\n noop: () => GenerationObserver.make(),\n\n /**\n * Debug printer to be used in unit-tests and browser devtools.\n */\n fromPrinter: (printer: ConsolePrinter) =>\n GenerationObserver.make({\n onBlock: (block) =>\n Effect.sync(() => {\n if (block.pending) {\n return; // Only prints full blocks (better for unit-tests and browser devtools).\n }\n printer.printContentBlock(block);\n }),\n onMessage: (message) =>\n Effect.sync(() => {\n if (message.sender.role === 'assistant') {\n return; // Skip assistant messages since they are printed in the `onBlock` callback.\n }\n printer.printMessage(message);\n }),\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR') {}\n\n/**\n * Parsed error from the anthropic API.\n */\nexport class AnthropicError extends BaseError.extend('ANTHROPIC_ERROR') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiError, AiLanguageModel, type AiTool, type AiToolkit } from '@effect/ai';\nimport { Chunk, Effect, type Schema, Stream } from 'effect';\n\nimport {\n type AiInputPreprocessingError,\n AiParser,\n AiPreprocessor,\n type AiToolNotFoundError,\n type ToolExecutionService,\n type ToolResolverService,\n callTool,\n getToolCalls,\n} from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { todo } from '@dxos/debug';\nimport { Obj } from '@dxos/echo';\nimport { TracingService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { type AiAssistantError } from '../errors';\n\nimport { mapAiError } from './error-handling';\nimport { formatSystemPrompt, formatUserPrompt } from './format';\nimport { GenerationObserver } from './observer';\n\nexport type AiSessionRunError = AiError.AiError | AiInputPreprocessingError | AiToolNotFoundError | AiAssistantError;\n\nexport type AiSessionRunRequirements =\n | AiLanguageModel.AiLanguageModel\n | ToolExecutionService\n | ToolResolverService\n | TracingService;\n\nexport type AiSessionRunParams<Tools extends AiTool.Any> = {\n prompt: string;\n system?: string;\n history?: DataType.Message[];\n objects?: Obj.Any[];\n blueprints?: Blueprint.Blueprint[];\n toolkit?: AiToolkit.ToHandler<Tools>;\n observer?: GenerationObserver;\n};\n\nexport type AiSessionOptions = {};\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch).\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\nexport class AiSession {\n /** Prevents concurrent execution of session. */\n private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));\n\n /** Message history from queue. */\n // TODO(burdon): Evolve into supporting a git-like graph of messages.\n private _history: DataType.Message[] = [];\n\n /** Pending messages for this session (incl. the current prompt). */\n private _pending: DataType.Message[] = [];\n\n constructor(private readonly _options: AiSessionOptions = {}) {}\n\n run = <Tools extends AiTool.Any>({\n prompt,\n system: systemTemplate,\n history = [],\n objects = [],\n blueprints = [],\n toolkit,\n observer = GenerationObserver.noop(),\n }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>\n Effect.gen(this, function* () {\n this._history = [...history];\n this._pending = [];\n const pending = this._pending;\n\n const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {\n pending.push(message);\n yield* observer.onMessage(message);\n yield* TracingService.emitConverationMessage(message);\n return message;\n });\n\n // Submit the prompt.\n // TODO(burdon): Remove if cancelled?\n const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));\n\n // Generate system and prompt messages.\n const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });\n\n // Tool call loop.\n do {\n log('request', {\n prompt: promptMessage,\n system: { snippet: createSnippet(system), length: system.length },\n pending: this._pending.length,\n history: this._history.length,\n objects: objects?.length ?? 0,\n });\n\n const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);\n\n // Execute the stream request.\n const blocks = yield* AiLanguageModel.streamText({\n prompt,\n system,\n toolkit,\n disableToolCallResolution: true,\n }).pipe(\n Stream.catchTag(\n 'AiError',\n Effect.fnUntraced(function* (err) {\n return yield* Effect.fail(yield* mapAiError(err));\n }),\n ),\n AiParser.parseResponse({\n onBegin: () => observer.onBegin(),\n onBlock: (block) => observer.onBlock(block),\n onPart: (part) => observer.onPart(part),\n onEnd: (summary) => observer.onEnd(summary),\n }),\n Stream.runCollect,\n Effect.map(Chunk.toArray),\n );\n\n // Create the response message.\n const response = yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'assistant' },\n blocks,\n }),\n );\n\n // Parse the response for tool calls.\n const toolCalls = getToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n } else if (!toolkit) {\n throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?\n }\n\n // Execute the tool calls.\n // TODO(burdon): Retry errors? Write result when each completes individually?\n const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {\n return callTool(toolkit, toolCall).pipe(\n Effect.provide(\n TracingService.layerSubframe((context) => ({\n ...context,\n parentMessage: response.id,\n toolCallId: toolCall.toolCallId,\n })),\n ),\n );\n });\n\n // Add to queue and continue loop.\n yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: toolResults,\n }),\n );\n } while (true);\n\n log('done', { pending: this._pending.length });\n return this._pending;\n }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));\n\n /**\n * @deprecated\n */\n // TODO(burdon): Implement or remove.\n async runStructured<S extends Schema.Schema.AnyNoContext>(\n _schema: S,\n _options: AiSessionRunParams<AiTool.Any>,\n ): Promise<Schema.Schema.Type<S>> {\n return todo();\n // const parser = structuredOutputParser(schema);\n // const result = await this.run({\n // ...options,\n // executableTools: [...(options.executableTools ?? []), parser.tool],\n // });\n // return parser.getResult(result);\n }\n}\n\nconst createSnippet = (text: string, len = 32) =>\n text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { AiError } from '@effect/ai';\nimport { HttpClientError } from '@effect/platform';\nimport { Effect, Schema } from 'effect';\n\nimport { AnthropicError } from '../errors';\n\nconst AnthropicErrorResponse = Schema.Struct({\n type: Schema.Literal('error'),\n error: Schema.Struct({\n type: Schema.String,\n message: Schema.String,\n }),\n});\n\nexport const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>\n Effect.gen(function* () {\n const cause = err.cause;\n if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {\n const body = yield* cause.response.json.pipe(\n Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),\n );\n\n const parsedCause = new AnthropicError(`${body.error.type}: ${body.error.message}`);\n return new AiError.AiError({\n description: body.error.message,\n module: err.module,\n method: err.method,\n cause: parsedCause,\n });\n }\n return err;\n }).pipe(Effect.catchAll(() => Effect.succeed(err)));\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Array, Effect, Option, pipe } from 'effect';\n\nimport { Template } from '@dxos/blueprints';\nimport { Obj } from '@dxos/echo';\nimport { ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type ContentBlock, DataType } from '@dxos/schema';\nimport { trim } from '@dxos/util';\n\nimport { AiAssistantError } from '../errors';\n\nimport { ArtifactDiffResolver } from './artifact-diff';\nimport { type AiSessionRunParams } from './session';\n\n/**\n * Formats the system prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\nexport const formatSystemPrompt = ({\n system,\n blueprints = [],\n objects = [],\n}: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>\n Effect.gen(function* () {\n const blueprintDefs = yield* pipe(\n blueprints,\n Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),\n Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(\n Array.map(\n (template) => trim`\n <blueprint>\n ${Template.process(template.value.content)}\n </blueprint>\n `,\n ),\n ),\n Effect.map((blueprints) =>\n blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\\n\\n') : undefined,\n ),\n );\n\n const objectDefs = yield* pipe(\n objects,\n Effect.forEach((object) =>\n Effect.succeed(trim`\n <object>\n <dxn>${Obj.getDXN(object)}</dxn>\n <typename>${Obj.getTypename(object)}</typename>\n </object>\n `),\n ),\n Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\\n\\n') : undefined)),\n );\n\n return yield* pipe(\n Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),\n Effect.map((parts) => parts.join('\\n\\n')),\n );\n });\n\n/**\n * Formats the user prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\n// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)\nexport const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>) =>\n Effect.gen(function* () {\n const blocks: ContentBlock.Any[] = [];\n\n // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.\n const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);\n if (Option.isSome(artifactDiffResolver)) {\n const versions = gatherObjectVersions(history);\n const artifactDiff = yield* Effect.tryPromise({\n try: () =>\n artifactDiffResolver.value.resolve(\n [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),\n ),\n catch: AiAssistantError.wrap('Artifact diff resolution error'),\n });\n\n log('version', { artifactDiff, versions });\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n blocks.push({ _tag: 'anchor', objectId: id, version });\n }\n\n if (artifactDiff.size > 0) {\n blocks.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [...blocks, { _tag: 'text', text: prompt }],\n });\n });\n\nconst gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {\n const artifactIds = new Map<ObjectId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.blocks) {\n if (block._tag === 'anchor') {\n artifactIds.set(block.objectId, block.version as ObjectVersion);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,\n): ContentBlock.Any => {\n return {\n _tag: 'text',\n // TODO(dmaretskyi): Does this need to be a special content-block?\n disposition: 'artifact-update',\n text: trim`\n The following artifacts have been updated since the last message:\n ${[...artifactDiff.entries()]\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiTool, AiToolkit } from '@effect/ai';\nimport { type Context, Effect } from 'effect';\n\nimport { ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { isNotFalsy } from '@dxos/util';\n\nexport type ToolkitParams<Tools extends AiTool.Any> = {\n toolkit?: AiToolkit.AiToolkit<Tools>;\n toolIds?: ToolId[];\n blueprints?: Blueprint.Blueprint[];\n};\n\n/**\n * Build a combined toolkit from the blueprint tools and the provided toolkit.\n */\nexport const createToolkit = <Tools extends AiTool.Any>({\n toolkit: toolkitParam,\n toolIds = [],\n blueprints = [],\n}: ToolkitParams<Tools>) =>\n Effect.gen(function* () {\n const blueprintToolkit = yield* ToolResolverService.resolveToolkit([\n ...blueprints.flatMap(({ tools }) => tools),\n ...toolIds,\n ]);\n\n const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> = yield* blueprintToolkit.toContext(\n ToolExecutionService.handlersFor(blueprintToolkit),\n );\n\n const toolkit = AiToolkit.merge(...[toolkitParam, blueprintToolkit].filter(isNotFalsy));\n return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as Effect.Effect<\n AiToolkit.ToHandler<any>,\n never,\n AiTool.ToHandler<Tools>\n >;\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { getVersion } from '@dxos/echo-db';\nimport { type AnyEchoObject, ObjectId } from '@dxos/echo-schema';\nimport { type ContentBlock } from '@dxos/schema';\n\n// TODO(dmaretskyi): Extract.\nconst ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;\n\nconst VersionPinSchema = Schema.Struct({\n // TODO(dmaretskyi): Use Ref when those support encoding.\n objectId: ObjectId,\n // TODO(dmaretskyi): Could be opaque.\n version: ObjectVersionSchema,\n});\n\n/**\n * Used to pin a specific version of an object during the course of a conversation.\n * This allows us to detect when the object changes during the course of the conversation.\n */\nexport interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}\n\nexport const VersionPin: typeof VersionPinSchema & {\n DISPOSITION: 'version-pin';\n fromObject: (object: AnyEchoObject) => VersionPin;\n createBlock: (pin: VersionPin) => ContentBlock.Any;\n} = class extends VersionPinSchema {\n static readonly DISPOSITION = 'version-pin';\n static fromObject(object: AnyEchoObject): VersionPin {\n return VersionPin.make({\n objectId: object.id,\n version: getVersion(object),\n });\n }\n\n static createBlock(pin: VersionPin): ContentBlock.Any {\n return {\n _tag: 'json',\n disposition: VersionPin.DISPOSITION,\n data: JSON.st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BC,QAAOC;AAEnC,IAAMC,mBAAmBF,QAAOG,OAAO;;EAErCC,UAAUC;;EAEVC,SAASP;AACX,CAAA;AAQO,IAAMQ,cAAAA,SAIT,cAAcL,iBAAAA;EAEhB,OAAOM,WAAWC,QAAmC;AACnD,WAAOF,WAAWG,KAAK;MACrBN,UAAUK,OAAOE;MACjBL,SAASM,WAAWH,MAAAA;IACtB,CAAA;EACF;EAEA,OAAOI,YAAYC,KAAmC;AACpD,WAAO;MACLC,MAAM;MACNC,aAAaT,WAAWU;MACxBC,MAAMC,KAAKC,UAAUN,GAAAA;IACvB;EACF;AACF,GAfEO,kBAAA,QAAgBJ,eAAc,aAAA,GAAA;",
6
- "names": ["Context", "ArtifactDiffResolver", "Context", "Tag", "Effect", "Function", "GenerationObserver", "Object", "freeze", "make", "onBegin", "Function", "constant", "Effect", "void", "onPart", "onBlock", "onEnd", "onMessage", "noop", "fromPrinter", "printer", "block", "sync", "pending", "printContentBlock", "message", "sender", "role", "printMessage", "BaseError", "AiAssistantError", "BaseError", "extend", "AnthropicError", "AiLanguageModel", "Chunk", "Effect", "Stream", "AiParser", "AiPreprocessor", "callTool", "getToolCalls", "todo", "Obj", "TracingService", "log", "DataType", "AiError", "HttpClientError", "Effect", "Schema", "AnthropicErrorResponse", "Schema", "Struct", "type", "Literal", "error", "String", "message", "mapAiError", "err", "Effect", "gen", "cause", "HttpClientError", "isHttpClientError", "reason", "body", "response", "json", "pipe", "flatMap", "decodeUnknown", "exact", "parsedCause", "AnthropicError", "AiError", "description", "module", "method", "catchAll", "succeed", "Array", "Effect", "Option", "pipe", "Template", "Obj", "ObjectVersion", "DatabaseService", "log", "DataType", "trim", "formatSystemPrompt", "system", "blueprints", "objects", "Effect", "gen", "blueprintDefs", "pipe", "forEach", "blueprint", "succeed", "instructions", "flatMap", "template", "DatabaseService", "loadOption", "source", "map", "Array", "filter", "Option", "isSome", "trim", "Template", "process", "value", "content", "length", "join", "undefined", "objectDefs", "object", "Obj", "getDXN", "getTypename", "def", "parts", "formatUserPrompt", "prompt", "history", "blocks", "artifactDiffResolver", "serviceOption", "ArtifactDiffResolver", "versions", "gatherObjectVersions", "artifactDiff", "tryPromise", "try", "resolve", "entries", "id", "version", "lastVersion", "catch", "AiAssistantError", "wrap", "log", "ObjectVersion", "equals", "get", "delete", "push", "_tag", "objectId", "size", "createArtifactUpdateBlock", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "text", "messages", "artifactIds", "Map", "message", "block", "set", "disposition", "diff", "AiSession", "runStructured", "_schema", "_options", "todo", "_semaphore", "_history", "_pending", "run", "Effect", "runSync", "makeSemaphore", "prompt", "system", "systemTemplate", "history", "objects", "blueprints", "toolkit", "observer", "GenerationObserver", "noop", "gen", "pending", "submitMessage", "fnUntraced", "message", "push", "onMessage", "TracingService", "emitConverationMessage", "promptMessage", "formatUserPrompt", "formatSystemPrompt", "log", "snippet", "createSnippet", "length", "AiPreprocessor", "preprocessAiInput", "blocks", "AiLanguageModel", "streamText", "disableToolCallResolution", "pipe", "Stream", "catchTag", "err", "fail", "mapAiError", "AiParser", "parseResponse", "onBegin", "onBlock", "block", "onPart", "part", "onEnd", "summary", "runCollect", "map", "Chunk", "toArray", "response", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "toolCalls", "getToolCalls", "Error", "toolResults", "forEach", "toolCall", "callTool", "provide", "layerSubframe", "context", "parentMessage", "id", "toolCallId", "withPermits", "withSpan", "text", "len", "slice", "join", "AiToolkit", "Effect", "ToolExecutionService", "ToolResolverService", "isNotFalsy", "createToolkit", "toolkit", "toolkitParam", "toolIds", "blueprints", "Effect", "gen", "blueprintToolkit", "ToolResolverService", "resolveToolkit", "flatMap", "tools", "blueprintToolkitHandler", "toContext", "ToolExecutionService", "handlersFor", "AiToolkit", "merge", "filter", "isNotFalsy", "pipe", "provide", "Schema", "getVersion", "ObjectId", "ObjectVersionSchema", "Schema", "Unknown", "VersionPinSchema", "Struct", "objectId", "ObjectId", "version", "VersionPin", "fromObject", "object", "make", "id", "getVersion", "createBlock", "pin", "_tag", "disposition", "DISPOSITION", "data", "JSON", "stringify", "_define_property"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/session/artifact-diff.ts", "../../../src/session/observer.ts", "../../../src/errors.ts", "../../../src/session/session.ts", "../../../src/session/error-handling.ts", "../../../src/session/format.ts", "../../../src/session/toolkit.ts", "../../../src/session/version-pin.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n *\n * Can be optionally provided to the session run call.\n */\n// TODO(dmaretskyi): Convert to Context.Reference\nexport class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<\n ArtifactDiffResolver,\n ArtifactDiffResolver.Service\n>() {}\n\nexport namespace ArtifactDiffResolver {\n export type Service = {\n resolve: (\n artifacts: {\n id: ObjectId;\n lastVersion: ObjectVersion;\n }[],\n ) => Promise<\n Map<\n ObjectId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n >;\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Function } from 'effect';\n\nimport { type AiParser, type ConsolePrinter } from '@dxos/ai';\nimport { type DataType } from '@dxos/schema';\n\n/**\n * Live observer of the generation process.\n */\nexport interface GenerationObserver extends AiParser.ParseResponseCallbacks {\n /**\n * Complete messages fired during the session, both from the model and from the user.\n * This message will contain all message blocks emitted through the `onBlock` callback.\n */\n onMessage: (message: DataType.Message) => Effect.Effect<void>;\n}\n\nexport const GenerationObserver = Object.freeze({\n make: ({\n onBegin = Function.constant(Effect.void),\n onPart = Function.constant(Effect.void),\n onBlock = Function.constant(Effect.void),\n onEnd = Function.constant(Effect.void),\n onMessage = Function.constant(Effect.void),\n }: Partial<GenerationObserver> = {}): GenerationObserver => ({\n onBegin,\n onPart,\n onBlock,\n onEnd,\n onMessage,\n }),\n\n noop: () => GenerationObserver.make(),\n\n /**\n * Debug printer to be used in unit-tests and browser devtools.\n */\n fromPrinter: (printer: ConsolePrinter) =>\n GenerationObserver.make({\n onBlock: (block) =>\n Effect.sync(() => {\n if (block.pending) {\n return; // Only prints full blocks (better for unit-tests and browser devtools).\n }\n printer.printContentBlock(block);\n }),\n onMessage: (message) =>\n Effect.sync(() => {\n if (message.sender.role === 'assistant') {\n return; // Skip assistant messages since they are printed in the `onBlock` callback.\n }\n printer.printMessage(message);\n }),\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR') {}\n\n/**\n * Parsed error from the anthropic API.\n */\nexport class AnthropicError extends BaseError.extend('ANTHROPIC_ERROR') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiError, AiLanguageModel, type AiTool, type AiToolkit } from '@effect/ai';\nimport { Chunk, Effect, type Schema, Stream } from 'effect';\n\nimport {\n type AiInputPreprocessingError,\n AiParser,\n AiPreprocessor,\n type AiToolNotFoundError,\n type ToolExecutionService,\n type ToolResolverService,\n callTool,\n getToolCalls,\n} from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { todo } from '@dxos/debug';\nimport { Obj } from '@dxos/echo';\nimport { TracingService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { type AiAssistantError } from '../errors';\n\nimport { mapAiError } from './error-handling';\nimport { formatSystemPrompt, formatUserPrompt } from './format';\nimport { GenerationObserver } from './observer';\n\nexport type AiSessionRunError = AiError.AiError | AiInputPreprocessingError | AiToolNotFoundError | AiAssistantError;\n\nexport type AiSessionRunRequirements =\n | AiLanguageModel.AiLanguageModel\n | ToolExecutionService\n | ToolResolverService\n | TracingService;\n\nexport type AiSessionRunParams<Tools extends AiTool.Any> = {\n prompt: string;\n system?: string;\n history?: DataType.Message[];\n objects?: Obj.Any[];\n blueprints?: Blueprint.Blueprint[];\n toolkit?: AiToolkit.ToHandler<Tools>;\n observer?: GenerationObserver;\n};\n\nexport type AiSessionOptions = {};\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch).\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\nexport class AiSession {\n /** Prevents concurrent execution of session. */\n private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));\n\n /** Message history from queue. */\n // TODO(burdon): Evolve into supporting a git-like graph of messages.\n private _history: DataType.Message[] = [];\n\n /** Pending messages for this session (incl. the current prompt). */\n private _pending: DataType.Message[] = [];\n\n constructor(private readonly _options: AiSessionOptions = {}) {}\n\n run = <Tools extends AiTool.Any>({\n prompt,\n system: systemTemplate,\n history = [],\n objects = [],\n blueprints = [],\n toolkit,\n observer = GenerationObserver.noop(),\n }: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>\n Effect.gen(this, function* () {\n this._history = [...history];\n this._pending = [];\n const pending = this._pending;\n\n const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {\n pending.push(message);\n yield* observer.onMessage(message);\n yield* TracingService.emitConverationMessage(message);\n return message;\n });\n\n // Submit the prompt.\n // TODO(burdon): Remove if cancelled?\n const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));\n\n // Generate system and prompt messages.\n const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });\n\n // Tool call loop.\n do {\n log('request', {\n prompt: promptMessage,\n system: { snippet: createSnippet(system), length: system.length },\n pending: this._pending.length,\n history: this._history.length,\n objects: objects?.length ?? 0,\n });\n\n const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);\n\n // Execute the stream request.\n const blocks = yield* AiLanguageModel.streamText({\n prompt,\n system,\n toolkit,\n disableToolCallResolution: true,\n }).pipe(\n Stream.catchTag(\n 'AiError',\n Effect.fnUntraced(function* (err) {\n return yield* Effect.fail(yield* mapAiError(err));\n }),\n ),\n AiParser.parseResponse({\n onBegin: () => observer.onBegin(),\n onBlock: (block) => observer.onBlock(block),\n onPart: (part) => observer.onPart(part),\n onEnd: (summary) => observer.onEnd(summary),\n }),\n Stream.runCollect,\n Effect.map(Chunk.toArray),\n );\n\n // Create the response message.\n const response = yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'assistant' },\n blocks,\n }),\n );\n\n // Parse the response for tool calls.\n const toolCalls = getToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n } else if (!toolkit) {\n throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?\n }\n\n // Execute the tool calls.\n // TODO(burdon): Retry errors? Write result when each completes individually?\n const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {\n return callTool(toolkit, toolCall).pipe(\n Effect.provide(\n TracingService.layerSubframe((context) => ({\n ...context,\n parentMessage: response.id,\n toolCallId: toolCall.toolCallId,\n })),\n ),\n );\n });\n\n // Add to queue and continue loop.\n yield* submitMessage(\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: toolResults,\n }),\n );\n } while (true);\n\n log('done', { pending: this._pending.length });\n return this._pending;\n }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));\n\n /**\n * @deprecated\n */\n // TODO(burdon): Implement or remove.\n async runStructured<S extends Schema.Schema.AnyNoContext>(\n _schema: S,\n _options: AiSessionRunParams<AiTool.Any>,\n ): Promise<Schema.Schema.Type<S>> {\n return todo();\n // const parser = structuredOutputParser(schema);\n // const result = await this.run({\n // ...options,\n // executableTools: [...(options.executableTools ?? []), parser.tool],\n // });\n // return parser.getResult(result);\n }\n}\n\nconst createSnippet = (text: string, len = 32) =>\n text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { AiError } from '@effect/ai';\nimport { HttpClientError } from '@effect/platform';\nimport { Effect, Schema } from 'effect';\n\nimport { AnthropicError } from '../errors';\n\nconst AnthropicErrorResponse = Schema.Struct({\n type: Schema.Literal('error'),\n error: Schema.Struct({\n type: Schema.String,\n message: Schema.String,\n }),\n});\n\nexport const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>\n Effect.gen(function* () {\n const cause = err.cause;\n if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {\n const body = yield* cause.response.json.pipe(\n Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),\n );\n\n const parsedCause = new AnthropicError(`${body.error.type}: ${body.error.message}`);\n return new AiError.AiError({\n description: body.error.message,\n module: err.module,\n method: err.method,\n cause: parsedCause,\n });\n }\n return err;\n }).pipe(Effect.catchAll(() => Effect.succeed(err)));\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Array, Effect, Option, pipe } from 'effect';\n\nimport { Template } from '@dxos/blueprints';\nimport { Obj } from '@dxos/echo';\nimport { ObjectVersion } from '@dxos/echo-db';\nimport { type ObjectId } from '@dxos/echo-schema';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type ContentBlock, DataType } from '@dxos/schema';\nimport { trim } from '@dxos/util';\n\nimport { AiAssistantError } from '../errors';\n\nimport { ArtifactDiffResolver } from './artifact-diff';\nimport { type AiSessionRunParams } from './session';\n\n/**\n * Formats the system prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\nexport const formatSystemPrompt = ({\n system,\n blueprints = [],\n objects = [],\n}: Pick<AiSessionRunParams<any>, 'system' | 'blueprints' | 'objects'>) =>\n Effect.gen(function* () {\n const blueprintDefs = yield* pipe(\n blueprints,\n Effect.forEach((blueprint) => Effect.succeed(blueprint.instructions)),\n Effect.flatMap(Effect.forEach((template) => DatabaseService.loadOption(template.source))),\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(\n Array.map(\n (template) => trim`\n <blueprint>\n ${Template.process(template.value.content)}\n </blueprint>\n `,\n ),\n ),\n Effect.map((blueprints) =>\n blueprints.length > 0 ? ['## Blueprints Definitions', ...blueprints].join('\\n\\n') : undefined,\n ),\n );\n\n const objectDefs = yield* pipe(\n objects,\n Effect.forEach((object) =>\n Effect.succeed(trim`\n <object>\n <dxn>${Obj.getDXN(object)}</dxn>\n <typename>${Obj.getTypename(object)}</typename>\n </object>\n `),\n ),\n Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\\n\\n') : undefined)),\n );\n\n return yield* pipe(\n Effect.succeed([system, blueprintDefs, objectDefs].filter((def): def is string => def !== undefined)),\n Effect.map((parts) => parts.join('\\n\\n')),\n );\n });\n\n/**\n * Formats the user prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\n// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)\nexport const formatUserPrompt = ({ prompt, history = [] }: Pick<AiSessionRunParams<any>, 'prompt' | 'history'>) =>\n Effect.gen(function* () {\n const blocks: ContentBlock.Any[] = [];\n\n // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.\n const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);\n if (Option.isSome(artifactDiffResolver)) {\n const versions = gatherObjectVersions(history);\n const artifactDiff = yield* Effect.tryPromise({\n try: () =>\n artifactDiffResolver.value.resolve(\n [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),\n ),\n catch: AiAssistantError.wrap('Artifact diff resolution error'),\n });\n\n log('version', { artifactDiff, versions });\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n blocks.push({ _tag: 'anchor', objectId: id, version });\n }\n\n if (artifactDiff.size > 0) {\n blocks.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [...blocks, { _tag: 'text', text: prompt }],\n });\n });\n\nconst gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {\n const artifactIds = new Map<ObjectId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.blocks) {\n if (block._tag === 'anchor') {\n artifactIds.set(block.objectId, block.version as ObjectVersion);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,\n): ContentBlock.Any => {\n return {\n _tag: 'text',\n // TODO(dmaretskyi): Does this need to be a special content-block?\n disposition: 'artifact-update',\n text: trim`\n The following artifacts have been updated since the last message:\n ${[...artifactDiff.entries()]\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiTool, AiToolkit } from '@effect/ai';\nimport { type Context, Effect } from 'effect';\n\nimport { ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';\nimport { type Blueprint } from '@dxos/blueprints';\nimport { isNotFalsy } from '@dxos/util';\n\nexport type ToolkitParams<Tools extends AiTool.Any> = {\n toolkit?: AiToolkit.AiToolkit<Tools>;\n toolIds?: ToolId[];\n blueprints?: Blueprint.Blueprint[];\n};\n\n/**\n * Build a combined toolkit from the blueprint tools and the provided toolkit.\n */\nexport const createToolkit = <Tools extends AiTool.Any>({\n toolkit: toolkitParam,\n toolIds = [],\n blueprints = [],\n}: ToolkitParams<Tools>) =>\n Effect.gen(function* () {\n const blueprintToolkit = yield* ToolResolverService.resolveToolkit([\n ...blueprints.flatMap(({ tools }) => tools),\n ...toolIds,\n ]);\n\n const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> = yield* blueprintToolkit.toContext(\n ToolExecutionService.handlersFor(blueprintToolkit),\n );\n\n const toolkit = AiToolkit.merge(...[toolkitParam, blueprintToolkit].filter(isNotFalsy));\n return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as Effect.Effect<\n AiToolkit.ToHandler<any>,\n never,\n AiTool.ToHandler<Tools>\n >;\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type ObjectVersion } from '@dxos/echo-db';\nimport { getVersion } from '@dxos/echo-db';\nimport { type AnyEchoObject, ObjectId } from '@dxos/echo-schema';\nimport { type ContentBlock } from '@dxos/schema';\n\n// TODO(dmaretskyi): Extract.\nconst ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;\n\nconst VersionPinSchema = Schema.Struct({\n // TODO(dmaretskyi): Use Ref when those support encoding.\n objectId: ObjectId,\n // TODO(dmaretskyi): Could be opaque.\n version: ObjectVersionSchema,\n});\n\n/**\n * Used to pin a specific version of an object during the course of a conversation.\n * This allows us to detect when the object changes during the course of the conversation.\n */\nexport interface VersionPin extends Schema.Schema.Type<typeof VersionPinSchema> {}\n\nexport const VersionPin: typeof VersionPinSchema & {\n DISPOSITION: 'version-pin';\n fromObject: (object: AnyEchoObject) => VersionPin;\n createBlock: (pin: VersionPin) => ContentBlock.Any;\n} = class extends VersionPinSchema {\n static readonly DISPOSITION = 'version-pin';\n static fromObject(object: AnyEchoObject): VersionPin {\n return VersionPin.make({\n objectId: object.id,\n version: getVersion(object),\n });\n }\n\n static createBlock(pin: VersionPin): ContentBlock.Any {\n return {\n _tag: 'json',\n disposition: VersionPin.DISPOSITION,\n data: JSON.stringify(pin),\n };\n }\n};\n"],
5
- "mappings": ";;;AAIA,SAASA,eAAe;AAcjB,IAAMC,uBAAN,cAAmCC,QAAQC,IAAI,sCAAA,EAAA,E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AIT,cAAcL,iBAAAA;EAEhB,OAAOM,WAAWC,QAAmC;AACnD,WAAOF,WAAWG,KAAK;MACrBN,UAAUK,OAAOE;MACjBL,SAASM,WAAWH,MAAAA;IACtB,CAAA;EACF;EAEA,OAAOI,YAAYC,KAAmC;AACpD,WAAO;MACLC,MAAM;MACNC,aAAaT,WAAWU;MACxBC,MAAMC,KAAKC,UAAUN,GAAAA;IACvB;EACF;AACF,GAfEO,kBAAA,QAAgBJ,eAAc,aAAA,GAAA;",
6
- "names": ["Context", "ArtifactDiffResolver", "Context", "Tag", "Effect", "Function", "GenerationObserver", "Object", "freeze", "make", "onBegin", "Function", "constant", "Effect", "void", "onPart", "onBlock", "onEnd", "onMessage", "noop", "fromPrinter", "printer", "block", "sync", "pending", "printContentBlock", "message", "sender", "role", "printMessage", "BaseError", "AiAssistantError", "BaseError", "extend", "AnthropicError", "AiLanguageModel", "Chunk", "Effect", "Stream", "AiParser", "AiPreprocessor", "callTool", "getToolCalls", "todo", "Obj", "TracingService", "log", "DataType", "AiError", "HttpClientError", "Effect", "Schema", "AnthropicErrorResponse", "Schema", "Struct", "type", "Literal", "error", "String", "message", "mapAiError", "err", "Effect", "gen", "cause", "HttpClientError", "isHttpClientError", "reason", "body", "response", "json", "pipe", "flatMap", "decodeUnknown", "exact", "parsedCause", "AnthropicError", "AiError", "description", "module", "method", "catchAll", "succeed", "Array", "Effect", "Option", "pipe", "Template", "Obj", "ObjectVersion", "DatabaseService", "log", "DataType", "trim", "formatSystemPrompt", "system", "blueprints", "objects", "Effect", "gen", "blueprintDefs", "pipe", "forEach", "blueprint", "succeed", "instructions", "flatMap", "template", "DatabaseService", "loadOption", "source", "map", "Array", "filter", "Option", "isSome", "trim", "Template", "process", "value", "content", "length", "join", "undefined", "objectDefs", "object", "Obj", "getDXN", "getTypename", "def", "parts", "formatUserPrompt", "prompt", "history", "blocks", "artifactDiffResolver", "serviceOption", "ArtifactDiffResolver", "versions", "gatherObjectVersions", "artifactDiff", "tryPromise", "try", "resolve", "entries", "id", "version", "lastVersion", "catch", "AiAssistantError", "wrap", "log", "ObjectVersion", "equals", "get", "delete", "push", "_tag", "objectId", "size", "createArtifactUpdateBlock", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "text", "messages", "artifactIds", "Map", "message", "block", "set", "disposition", "diff", "AiSession", "runStructured", "_schema", "_options", "todo", "_semaphore", "_history", "_pending", "run", "Effect", "runSync", "makeSemaphore", "prompt", "system", "systemTemplate", "history", "objects", "blueprints", "toolkit", "observer", "GenerationObserver", "noop", "gen", "pending", "submitMessage", "fnUntraced", "message", "push", "onMessage", "TracingService", "emitConverationMessage", "promptMessage", "formatUserPrompt", "formatSystemPrompt", "log", "snippet", "createSnippet", "length", "AiPreprocessor", "preprocessAiInput", "blocks", "AiLanguageModel", "streamText", "disableToolCallResolution", "pipe", "Stream", "catchTag", "err", "fail", "mapAiError", "AiParser", "parseResponse", "onBegin", "onBlock", "block", "onPart", "part", "onEnd", "summary", "runCollect", "map", "Chunk", "toArray", "response", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "toolCalls", "getToolCalls", "Error", "toolResults", "forEach", "toolCall", "callTool", "provide", "layerSubframe", "context", "parentMessage", "id", "toolCallId", "withPermits", "withSpan", "text", "len", "slice", "join", "AiToolkit", "Effect", "ToolExecutionService", "ToolResolverService", "isNotFalsy", "createToolkit", "toolkit", "toolkitParam", "toolIds", "blueprints", "Effect", "gen", "blueprintToolkit", "ToolResolverService", "resolveToolkit", "flatMap", "tools", "blueprintToolkitHandler", "toContext", "ToolExecutionService", "handlersFor", "AiToolkit", "merge", "filter", "isNotFalsy", "pipe", "provide", "Schema", "getVersion", "ObjectId", "ObjectVersionSchema", "Schema", "Unknown", "VersionPinSchema", "Struct", "objectId", "ObjectId", "version", "VersionPin", "fromObject", "object", "make", "id", "getVersion", "createBlock", "pin", "_tag", "disposition", "DISPOSITION", "data", "JSON", "stringify", "_define_property"]
7
- }