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

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 (112) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +118 -161
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +977 -156
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  8. package/dist/lib/node-esm/extraction/index.mjs +118 -161
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +977 -156
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/conversation/context.d.ts +14 -7
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +11 -12
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts.map +1 -1
  18. package/dist/types/src/errors.d.ts +14 -18
  19. package/dist/types/src/errors.d.ts.map +1 -1
  20. package/dist/types/src/execution-graph.d.ts +85 -0
  21. package/dist/types/src/execution-graph.d.ts.map +1 -0
  22. package/dist/types/src/execution-graph.test.d.ts +2 -0
  23. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  24. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  25. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +60 -52
  26. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  27. package/dist/types/src/extraction/extraction.d.ts +24 -13
  28. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  29. package/dist/types/src/extraction/quotes.d.ts +1 -1
  30. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  31. package/dist/types/src/functions/services.d.ts +18 -5
  32. package/dist/types/src/functions/services.d.ts.map +1 -1
  33. package/dist/types/src/index.d.ts +2 -1
  34. package/dist/types/src/index.d.ts.map +1 -1
  35. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  36. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  37. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  38. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  39. package/dist/types/src/session/error-handling.d.ts +2 -2
  40. package/dist/types/src/session/error-handling.d.ts.map +1 -1
  41. package/dist/types/src/session/format.d.ts +4 -174
  42. package/dist/types/src/session/format.d.ts.map +1 -1
  43. package/dist/types/src/session/index.d.ts +1 -0
  44. package/dist/types/src/session/index.d.ts.map +1 -1
  45. package/dist/types/src/session/observer.d.ts +3 -3
  46. package/dist/types/src/session/observer.d.ts.map +1 -1
  47. package/dist/types/src/session/session.d.ts +15 -11
  48. package/dist/types/src/session/session.d.ts.map +1 -1
  49. package/dist/types/src/session/toolkit.d.ts +7 -6
  50. package/dist/types/src/session/toolkit.d.ts.map +1 -1
  51. package/dist/types/src/session/version-pin.d.ts +3 -3
  52. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  53. package/dist/types/src/types/artifact.d.ts +20 -0
  54. package/dist/types/src/types/artifact.d.ts.map +1 -0
  55. package/dist/types/src/types/index.d.ts +2 -0
  56. package/dist/types/src/types/index.d.ts.map +1 -0
  57. package/dist/types/tsconfig.tsbuildinfo +1 -1
  58. package/package.json +28 -31
  59. package/src/conversation/context.ts +49 -17
  60. package/src/conversation/conversation.ts +28 -23
  61. package/src/diff.test.ts +3 -3
  62. package/src/diff.ts +5 -0
  63. package/src/execution-graph.test.ts +740 -0
  64. package/src/execution-graph.ts +509 -0
  65. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +2 -2
  66. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +46 -54
  67. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +10 -9
  68. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +38 -44
  69. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  70. package/src/extraction/extraction.ts +7 -6
  71. package/src/extraction/quotes.ts +2 -2
  72. package/src/functions/services.ts +93 -50
  73. package/src/index.ts +2 -1
  74. package/src/session/GenericToolkit.ts +130 -0
  75. package/src/session/artifact-diff.ts +2 -2
  76. package/src/session/error-handling.ts +6 -4
  77. package/src/session/format.test.ts +5 -4
  78. package/src/session/format.ts +17 -12
  79. package/src/session/index.ts +2 -0
  80. package/src/session/observer.ts +4 -3
  81. package/src/session/session.conversations.json +1 -0
  82. package/src/session/session.test.ts +51 -210
  83. package/src/session/session.ts +40 -28
  84. package/src/session/toolkit.ts +19 -13
  85. package/src/session/version-pin.ts +4 -5
  86. package/src/templates/{format.tpl → instructions/format.tpl} +1 -0
  87. package/src/templates/{system.tpl → instructions/system.tpl} +10 -12
  88. package/src/templates/system.ts +2 -2
  89. package/src/{types.ts → types/artifact.ts} +22 -3
  90. package/src/types/index.ts +5 -0
  91. package/dist/lib/browser/chunk-3K5SRE5A.mjs +0 -404
  92. package/dist/lib/browser/chunk-3K5SRE5A.mjs.map +0 -7
  93. package/dist/lib/browser/chunk-UB26N5UF.mjs +0 -89
  94. package/dist/lib/browser/chunk-UB26N5UF.mjs.map +0 -7
  95. package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +0 -13
  96. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +0 -91
  97. package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +0 -7
  98. package/dist/lib/node-esm/chunk-W7AIB6DP.mjs +0 -406
  99. package/dist/lib/node-esm/chunk-W7AIB6DP.mjs.map +0 -7
  100. package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs +0 -14
  101. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  102. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  103. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  104. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  105. package/dist/types/src/types.d.ts +0 -16
  106. package/dist/types/src/types.d.ts.map +0 -1
  107. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  108. package/src/session/version-pin.test.ts +0 -7
  109. package/src/summarization/summarization.test.ts +0 -197
  110. /package/dist/lib/browser/{named-entity-recognition-QPYHML66.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  111. /package/dist/lib/node-esm/{named-entity-recognition-2HDF46YX.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  112. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -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 from AI model.\n */\nexport class AiModelError extends BaseError.extend('AI_MODEL_ERROR', 'AI model error') {}\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AI_ASSISTANT_ERROR', 'AI assistant 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 { AiModelError } 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 AiModelError({\n message: body.error.message,\n context: { model: 'anthropic', type: body.error.type },\n });\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({ message: '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,EAAA;AAGjD;;;ACjBL,SAASC,QAAQC,gBAAgB;AAgB1B,IAAMC,qBAAqBC,OAAOC,OAAO;EAC9CC,MAAM,CAAC,EACLC,UAAUC,SAASC,SAASC,OAAOC,IAAI,GACvCC,SAASJ,SAASC,SAASC,OAAOC,IAAI,GACtCE,UAAUL,SAASC,SAASC,OAAOC,IAAI,GACvCG,QAAQN,SAASC,SAASC,OAAOC,IAAI,GACrCI,YAAYP,SAASC,SAASC,OAAOC,IAAI,EAAC,IACX,CAAC,OAA2B;IAC3DJ;IACAK;IACAC;IACAC;IACAC;EACF;EAEAC,MAAM,MAAMb,mBAAmBG,KAAI;;;;EAKnCW,aAAa,CAACC,YACZf,mBAAmBG,KAAK;IACtBO,SAAS,CAACM,UACRT,OAAOU,KAAK,MAAA;AACV,UAAID,MAAME,SAAS;AACjB;MACF;AACAH,cAAQI,kBAAkBH,KAAAA;IAC5B,CAAA;IACFJ,WAAW,CAACQ,YACVb,OAAOU,KAAK,MAAA;AACV,UAAIG,QAAQC,OAAOC,SAAS,aAAa;AACvC;MACF;AACAP,cAAQQ,aAAaH,OAAAA;IACvB,CAAA;EACJ,CAAA;AACJ,CAAA;;;ACrDA,SAASI,iBAAiB;AAKnB,IAAMC,eAAN,cAA2BC,UAAUC,OAAO,kBAAkB,gBAAA,EAAA;AAAmB;AAKjF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AAAA;OAClCR;GACJ;AAED,QAAMS,0BAAyE,OAAOL,iBAAiBM,UACrGC,qBAAqBC,YAAYR,gBAAAA,CAAAA;AAGnC,QAAMN,UAAUe,UAAUC,MAAK,GAAI;IAACf;IAAcK;IAAkBW,OAAOC,UAAAA,CAAAA;AAC3E,SAAO,OAAOlB,QAAQmB,KAAKf,QAAOgB,QAAQT,uBAAAA,CAAAA;AAK5C,CAAA;;;ACrCF,SAASU,UAAAA,eAAc;AAGvB,SAASC,kBAAkB;AAC3B,SAA6BC,gBAAgB;;;;;;;;;;;;;;;AAI7C,IAAMC,sBAAsBC,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", "AiModelError", "BaseError", "extend", "AiAssistantError", "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", "AiModelError", "context", "model", "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", "message", "log", "ObjectVersion", "equals", "get", "delete", "push", "_tag", "objectId", "size", "createArtifactUpdateBlock", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "text", "messages", "artifactIds", "Map", "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,14 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- combineNerTokens,
4
- createTokenGroups,
5
- extractFullEntities,
6
- getNer
7
- } from "./chunk-BCFXTNSK.mjs";
8
- export {
9
- combineNerTokens,
10
- createTokenGroups,
11
- extractFullEntities,
12
- getNer
13
- };
14
- //# sourceMappingURL=named-entity-recognition-2HDF46YX.mjs.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=version-pin.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"version-pin.test.d.ts","sourceRoot":"","sources":["../../../../src/session/version-pin.test.ts"],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=summarization.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"summarization.test.d.ts","sourceRoot":"","sources":["../../../../src/summarization/summarization.test.ts"],"names":[],"mappings":""}
@@ -1,16 +0,0 @@
1
- import { Schema } from 'effect';
2
- import { type ObjectId } from '@dxos/echo-schema';
3
- import { DXN, type SpaceId } from '@dxos/keys';
4
- /**
5
- * @deprecated
6
- */
7
- export declare const createArtifactElement: (id: ObjectId) => string;
8
- /**
9
- * A model-friendly way to reference an object.
10
- * Supports vairous formats that will be normalized to a DXN.
11
- */
12
- export declare const ArtifactId: Schema.Schema<string> & {
13
- toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;
14
- };
15
- export type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;
16
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,GAAG,EAAmB,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAGhE;;GAEG;AACH,eAAO,MAAM,qBAAqB,GAAI,IAAI,QAAQ,WAA4B,CAAC;AAE/E;;;GAGG;AAEH,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG;IAC/C,KAAK,EAAE,CAAC,SAAS,EAAE,UAAU,EAAE,aAAa,CAAC,EAAE,OAAO,KAAK,GAAG,CAAC;CA4BhE,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,UAAU,CAAC,CAAC"}
@@ -1,32 +0,0 @@
1
- // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
-
3
- exports[`AiSession > no tools 1`] = `
4
- [
5
- {
6
- "blocks": ReactiveArray [
7
- {
8
- "_tag": "text",
9
- "text": "Hello world!",
10
- },
11
- ],
12
- "created": "Sun, 20 Jul 2025 10:54:08 GMT",
13
- "id": "01K0KQGFTFV3GBKGEWZW67K8HK",
14
- "sender": {
15
- "role": "user",
16
- },
17
- },
18
- {
19
- "blocks": ReactiveArray [
20
- {
21
- "_tag": "text",
22
- "text": "Hi there! How can I help you today?",
23
- },
24
- ],
25
- "created": "2025-07-20T10:54:10.801Z",
26
- "id": "01K0KQGHVHJ37D4YG45WG090WV",
27
- "sender": {
28
- "role": "assistant",
29
- },
30
- },
31
- ]
32
- `;
@@ -1,7 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe } from 'vitest';
6
-
7
- describe('VersionPin', () => {});
@@ -1,197 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- // ISSUE(burdon): defineFunction
6
- // @ts-nocheck
7
-
8
- import { Schema, pipe } from 'effect';
9
- import { beforeAll, describe, test } from 'vitest';
10
-
11
- import { AiService, MixedStreamParser } from '@dxos/ai';
12
- import { Obj } from '@dxos/echo';
13
- import { type EchoDatabase } from '@dxos/echo-db';
14
- import { EchoTestBuilder } from '@dxos/echo-db/testing';
15
- import { FunctionExecutor, ServiceContainer, defineFunction } from '@dxos/functions';
16
- import { type ContentBlock, DataType } from '@dxos/schema';
17
- import { createTestData } from '@dxos/schema/testing';
18
- import { trim } from '@dxos/util';
19
-
20
- const summarizationFn = defineFunction({
21
- description: 'Summarize a document',
22
- inputSchema: Schema.Struct({
23
- document: Schema.optional(DataType.Text),
24
- transcript: Schema.Array(DataType.Message),
25
- }),
26
- outputSchema: DataType.Text,
27
- handler: async ({ data: { document, transcript }, context }) => {
28
- const ai = context.getService(AiService.AiService);
29
- const result = await new MixedStreamParser().parse(
30
- await ai.client.execStream({
31
- model: '@anthropic/claude-3-5-haiku-20241022',
32
- // TODO(burdon): Factor out and test prompts.
33
- systemPrompt: trim`
34
- Your job is to summarize a meeting transcript.
35
- Transcript Summarizer updates an existing summary within <summary> tags with a new transcript that is placed in <transcript> tags.
36
- Transcript Summarizer updates only the relevant parts of the summary.
37
- If there's no summary, create a new one.
38
- Transcript Summarizer outputs only the summary texts and nothing else.
39
- Transcript Summarizer keeps the original summary structure.
40
- Transcript Summarizer keeps the unrelated parts of the summary untouched.
41
- The Transcript Summarizer errs on the side of being too verbose.
42
- The Transcript Summarizer outputs the entire update summary.
43
- The summary is formatted as hierarchical markdown bullet points with no headings.
44
- The hierarchical structure is deeply nested.
45
- The Transcript Summarizer formats the bullets with "-" symbol as prefix and two spaces indentation.
46
- The Transcript Summarizer knows that the content of transcript will be updated solely by its output.
47
- The Transcript Summarizer outputs only the summary text.
48
- `,
49
- history: [
50
- Obj.make(DataType.Message, {
51
- created: new Date().toISOString(),
52
- sender: { role: 'user' },
53
- blocks: [
54
- {
55
- _tag: 'text',
56
- text: trim`
57
- <transcript>
58
- ${JSON.stringify(transcript, null, 2)}
59
- </transcript>
60
- `,
61
- },
62
- ...(document != null && document.content.length > 0
63
- ? [
64
- {
65
- _tag: 'text',
66
- text: trim`
67
- <summary>
68
- ${document.content}
69
- </summary>
70
- `,
71
- } satisfies ContentBlock.Text,
72
- ]
73
- : []),
74
- ],
75
- }),
76
- ],
77
- }),
78
- );
79
-
80
- return DataType.makeText(pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : '')));
81
- },
82
- });
83
-
84
- const refinementFn = defineFunction({
85
- description: 'Refine a summary',
86
- inputSchema: Schema.Struct({
87
- summaries: Schema.Array(DataType.Text),
88
- }),
89
- outputSchema: Schema.Struct({
90
- summary: DataType.Text,
91
- }),
92
- handler: async ({ data: { summaries }, context }) => {
93
- const ai = context.getService(AiService.AiService);
94
- const result = await new MixedStreamParser().parse(
95
- await ai.client.execStream({
96
- model: '@anthropic/claude-3-5-haiku-20241022',
97
- // TODO(burdon): Factor out and test prompts.
98
- systemPrompt: trim`
99
- You are a Transcript Summary Refiner.
100
- Transcript Summary Refiner works on a history of evolving summaries that were generated based on the transcript.
101
- The summaries are presented starting from the oldest to the newest.
102
- Each iteration of the summary contains a new part of the transcript.
103
- The Transcript Summary Refiner refines the summary based on the history of summaries.
104
- The Transcript Summary Refiner identifies any potential data lost between the iterations and adds its back to the output.
105
- The Transcript Summary Refiner updates the summary to be more structured.
106
- The Transcript Summary Refiner errs on the side of being too verbose.
107
- The Transcript Summary Refiner errs on keeping the original summary structure.
108
- The Transcript Summary Refiner outputs the entire update summary.
109
- The Transcript Summary is formatted as hierarchical markdown bullet points with no headings.
110
- The hierarchical structure is deeply nested.
111
- The Transcript Summary Refiner formats the bullets with "-" symbol as prefix and two spaces indentation.
112
- The Transcript Summary Refiner knows that the content of transcript will be updated solely by its output.
113
- The Transcript Summary Refiner outputs only the summary text.
114
- `,
115
- history: [
116
- Obj.make(DataType.Message, {
117
- created: new Date().toISOString(),
118
- sender: { role: 'user' },
119
- blocks: summaries.map(
120
- (summary) =>
121
- ({
122
- _tag: 'text',
123
- text: trim`
124
- <summary>
125
- ${summary.content}
126
- </summary>
127
- `,
128
- }) satisfies ContentBlock.Text,
129
- ),
130
- }),
131
- ],
132
- }),
133
- );
134
- return {
135
- summary: DataType.makeText(pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : ''))),
136
- };
137
- },
138
- });
139
-
140
- describe.skip('Summarization', () => {
141
- let builder: EchoTestBuilder;
142
- let db: EchoDatabase;
143
- let executor: FunctionExecutor;
144
-
145
- // TODO(burdon): Rewrite test.
146
- beforeAll(async () => {
147
- // TODO(dmaretskyi): Helper to scaffold this from a config.
148
- builder = await new EchoTestBuilder().open();
149
- const { db: db1 } = await builder.createDatabase({ indexing: { vector: true } });
150
- db = db1;
151
- executor = new FunctionExecutor(
152
- new ServiceContainer().setServices({
153
- ai: todo(),
154
- database: {
155
- db,
156
- },
157
- }),
158
- );
159
- });
160
-
161
- test('keeps transcript outline', { timeout: 1000_000 }, async () => {
162
- const { transcriptMessages } = createTestData();
163
-
164
- const summary = DataType.makeText();
165
-
166
- const summaries = [];
167
-
168
- for (let i = 0; i < transcriptMessages.length; i++) {
169
- const blocks = transcriptMessages.slice(Math.max(0, i - 2), i + 1);
170
- const result = await executor.invoke(summarizationFn, {
171
- document: summary,
172
- transcript: blocks,
173
- });
174
- summary.content = result.content;
175
- summaries.push(DataType.makeText(result.content));
176
-
177
- console.log(blocks.at(-1));
178
- console.log();
179
- console.log(summary.content);
180
- console.log();
181
-
182
- if (i % 3 === 0 && i > 0) {
183
- const history: any = summaries.slice(-5);
184
- const result = await executor.invoke(refinementFn, {
185
- summaries: history,
186
- });
187
- summary.content = result.summary.content;
188
- summaries.push(DataType.makeText(result.summary.content));
189
-
190
- console.log('REFINED');
191
- console.log();
192
- console.log(summary.content);
193
- console.log();
194
- }
195
- }
196
- });
197
- });