@dxos/assistant 0.8.4-main.1da679c → 0.8.4-main.1f223c7

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.
@@ -116,7 +116,7 @@ var insertReferences = (text, quotes) => {
116
116
  return text;
117
117
  };
118
118
 
119
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw
119
+ // raw-loader:./instructions.tpl?raw
120
120
  var instructions_default = 'You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ "quote": "earnings report", "id": "01JT0JP9AX0XKGZX4MV4B69VT6" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.';
121
121
 
122
122
  // src/extraction/extraction-llm-function/extraction-llm-function.ts
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
3
+ "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:./instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
4
4
  "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Expando } from '@dxos/echo-schema';\nimport { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nexport const ExtractionInput = Schema.Struct({\n message: DataType.Message,\n objects: Schema.optional(Schema.Array(Expando)),\n options: Schema.optional(\n Schema.Struct({\n timeout: Schema.optional(Schema.Number),\n fallbackToRaw: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nexport interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}\n\nexport const ExtractionOutput = Schema.Struct({\n message: DataType.Message,\n timeElapsed: Schema.Number,\n});\nexport interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}\n\nexport type ProcessTranscriptMessageParams = {\n input: ExtractionInput;\n function: FunctionDefinition<ExtractionInput, ExtractionOutput>;\n executor: FunctionExecutor;\n\n options?: {\n /**\n * Timeout for the entity extraction.\n */\n timeout?: number;\n\n /**\n * Fallback to raw text if the entity extraction fails.\n * Otherwise the function will throw an error.\n * @default false\n */\n fallbackToRaw?: boolean;\n };\n};\n\nexport type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Extract entities from the transcript message and add them to the message.\n */\n// TODO(dmaretskyi): Move context to a vector search index.\nexport const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {\n try {\n if (params.options?.timeout && params.options.timeout > 0) {\n return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);\n } else {\n return await params.executor.invoke(params.function, params.input);\n }\n } catch (error) {\n if (params.options?.fallbackToRaw) {\n log.warn('failed to process message, falling back to raw text', { error });\n return {\n message: params.input.message,\n timeElapsed: 0,\n };\n } else {\n throw error;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { AiService } from '@dxos/ai';\nimport { Obj } from '@dxos/echo';\nimport { create } from '@dxos/echo-schema';\nimport { type FunctionDefinition, defineFunction } from '@dxos/functions';\nimport { type ContentBlock, DataType } from '@dxos/schema';\n\nimport { AiSession } from '../../session';\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { ReferencedQuotes, insertReferences } from '../quotes';\n\nimport PROMPT from './instructions.tpl?raw';\n\nexport const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({\n description: 'Extract entities from the transcript message and add them to the message.',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, objects }, context }) => {\n const startTime = performance.now();\n const ai = context.getService(AiService.AiService);\n const session = new AiSession({ operationModel: 'configured' });\n const result = await session.runStructured(ReferencedQuotes, {\n generationOptions: {\n model: '@anthropic/claude-3-5-haiku-20241022',\n },\n client: ai.client,\n systemPrompt: PROMPT,\n history: [\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [\n {\n _tag: 'text',\n text: `<context>${JSON.stringify(objects)}</context>`,\n } satisfies ContentBlock.Text,\n {\n _tag: 'text',\n text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,\n } satisfies ContentBlock.Text,\n ],\n }),\n ],\n artifacts: [],\n prompt: '',\n tools: [],\n } as any); // TODO(burdon): Rewrite test.\n\n return {\n timeElapsed: performance.now() - startTime,\n message: create(DataType.Message, {\n ...message,\n blocks: message.blocks.map((block) =>\n block._tag !== 'transcript'\n ? block\n : {\n ...block,\n text: insertReferences(block.text, result),\n },\n ),\n }),\n };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Filter, Query } from '@dxos/echo';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { ObjectId } from '@dxos/echo-schema';\nimport { DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nexport const ReferencedQuotes = Schema.Struct({\n references: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n quote: Schema.String, // TODO(burdon): Quote?\n }),\n )\n .pipe(Schema.mutable)\n .annotations({\n // TODO(burdon): Does this description make sense?\n description: `\n The references to the context objects that are mentioned in the transcript. \n Quote should match the original transcript text exactly, while id is the id of the context object.\n `,\n }),\n});\nexport type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;\n\nexport const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {\n const references = await Promise.all(\n quotes.map(async (quote) => {\n const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();\n log.info('found quotes in vector index', { objects, quote });\n return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];\n }),\n );\n return { references: references.flat() };\n};\n\n/**\n * Finds and replaces all quotes with DXNs references.\n */\n// TODO(dmaretskyi): Lookup and verifiy ids from provided context.\nexport const insertReferences = (text: string, quotes: ReferencedQuotes) => {\n for (const quote of quotes.references) {\n if (!ObjectId.isValid(quote.id)) {\n continue;\n }\n\n // Use a case-insensitive regular expression to replace the quote.\n const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);\n }\n\n return text;\n};\n", "You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ \"quote\": \"earnings report\", \"id\": \"01JT0JP9AX0XKGZX4MV4B69VT6\" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { asyncTimeout } from '@dxos/async';\nimport { create } from '@dxos/echo-schema';\nimport { DatabaseService, defineFunction } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { findQuotes, insertReferences } from '../quotes';\n\n/**\n * Named Entity Recognition model\n */\n// TODO(mykola): Make it use vector index to query objects and not pass objects as input.\nexport const extractionNerFunction = defineFunction({\n description: 'Extracts named entities from a text',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, options }, context }) => {\n log.info('input', { message, options });\n const startTime = performance.now();\n const { db } = context.getService(DatabaseService);\n const { extractFullEntities } = await import('./named-entity-recognition');\n\n const entitiesPromise = Promise.all(\n message.blocks.map(async (block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return extractFullEntities(block.text);\n }),\n ).then((entities) => entities.flat());\n const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;\n\n log.info('entities', { entities });\n const quoteReferences = await findQuotes(\n entities.map((entity) => entity.word),\n db,\n );\n\n const blocksWithReferences = message.blocks.map((block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return { ...block, text: insertReferences(block._tag, quoteReferences) };\n });\n\n const messageWithReferences = create(DataType.Message, {\n ...message,\n blocks: blocksWithReferences,\n });\n\n log.info('output', { messageWithReferences });\n return {\n message: messageWithReferences,\n timeElapsed: performance.now() - startTime,\n };\n },\n});\n"],
5
5
  "mappings": ";;;;;;;;;;;AAIA,SAASA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AS;MAAEJ;MAASC;IAAQ,GAAA;;;;;;AACrC,UAAMI,YAAYC,YAAYC,IAAG;AACjC,UAAM,EAAEC,GAAE,IAAKN,QAAQO,WAAWC,eAAAA;AAClC,UAAM,EAAEC,qBAAAA,qBAAmB,IAAK,MAAM,OAAO,0CAAA;AAE7C,UAAMC,kBAAkBC,QAAQC,IAC9Bd,QAAQe,OAAOC,IAAI,OAAOC,UAAAA;AACxBC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAOR,qBAAoBM,MAAMG,IAAI;IACvC,CAAA,CAAA,EACAC,KAAK,CAACC,cAAaA,UAASC,KAAI,CAAA;AAClC,UAAMD,WAAWrB,SAASuB,UAAU,MAAMC,cAAab,iBAAiBX,QAAQuB,OAAO,IAAI,MAAMZ;AAEjGT,IAAAA,KAAIC,KAAK,YAAY;MAAEkB;IAAS,GAAA;;;;;;AAChC,UAAMI,kBAAkB,MAAMC,WAC5BL,SAASN,IAAI,CAACY,WAAWA,OAAOC,IAAI,GACpCrB,EAAAA;AAGF,UAAMsB,uBAAuB9B,QAAQe,OAAOC,IAAI,CAACC,UAAAA;AAC/CC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAO;QAAE,GAAGF;QAAOG,MAAMW,iBAAiBd,MAAME,MAAMO,eAAAA;MAAiB;IACzE,CAAA;AAEA,UAAMM,wBAAwBC,QAAOC,UAASC,SAAS;MACrD,GAAGnC;MACHe,QAAQe;IACV,CAAA;AAEA3B,IAAAA,KAAIC,KAAK,UAAU;MAAE4B;IAAsB,GAAA;;;;;;AAC3C,WAAO;MACLhC,SAASgC;MACTI,aAAa9B,YAAYC,IAAG,IAAKF;IACnC;EACF;AACF,CAAA;",
6
6
  "names": ["Schema", "asyncTimeout", "Expando", "log", "DataType", "ExtractionInput", "Struct", "message", "Message", "objects", "optional", "Array", "options", "timeout", "Number", "fallbackToRaw", "Boolean", "ExtractionOutput", "timeElapsed", "processTranscriptMessage", "params", "executor", "invoke", "function", "input", "error", "warn", "AiService", "Obj", "create", "defineFunction", "DataType", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "ReferencedQuotes", "Struct", "references", "Array", "id", "String", "quote", "pipe", "mutable", "annotations", "description", "findQuotes", "quotes", "db", "Promise", "all", "map", "objects", "query", "select", "text", "type", "run", "info", "length", "toString", "flat", "insertReferences", "isValid", "regex", "RegExp", "replace", "fromLocalObjectId", "extractionAnthropicFunction", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "objects", "context", "startTime", "performance", "now", "ai", "getService", "AiService", "session", "AiSession", "operationModel", "result", "runStructured", "ReferencedQuotes", "generationOptions", "model", "client", "systemPrompt", "PROMPT", "history", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "blocks", "_tag", "text", "JSON", "stringify", "artifacts", "prompt", "tools", "timeElapsed", "create", "map", "block", "insertReferences", "asyncTimeout", "create", "DatabaseService", "defineFunction", "invariant", "log", "DataType", "extractionNerFunction", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "options", "context", "log", "info", "startTime", "performance", "now", "db", "getService", "DatabaseService", "extractFullEntities", "entitiesPromise", "Promise", "all", "blocks", "map", "block", "invariant", "_tag", "text", "then", "entities", "flat", "timeout", "asyncTimeout", "quoteReferences", "findQuotes", "entity", "word", "blocksWithReferences", "insertReferences", "messageWithReferences", "create", "DataType", "Message", "timeElapsed"]
@@ -385,11 +385,11 @@ var createStructFieldsFromSchema = (schema) => {
385
385
  import defaultsDeep from "lodash.defaultsdeep";
386
386
  import { Template } from "@dxos/blueprints";
387
387
 
388
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw
388
+ // raw-loader:./format.tpl?raw
389
389
  var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\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## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
390
390
 
391
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw
392
- var system_default = "{{! System Prompt }}\n\n- You are a helpful assistant called Kai. \n- Your name is Kai and you are powered by different language models.\n- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.\n- In your initial greeting state your name and make some suggestions based on the current context objects.\n- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\n- Your task is to process user commands and questions and decide how best to respond.\n- In general be concise and direct.\n- Follow all instructions carefully.\n\n## Planning\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints and Artifacts\n\n- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.\n- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.\n- If it is ambiguous, query for existing artifacts first and then decide.\n- If you decide to create an artifact, call the associated tool to create the artifact.\n- Artifacts are stored in the database. Tools are used to create and query artifacts.\n- If you are unsure about creating an artifact ask the user for clarification.\n- Artifacts are mutable objects that can change over the course of the conversation.\n- Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.\n- You must never generate the id of the artifact; only recall the ids that are already in the history.\n- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.\n- You can add suggested actions at the end of your response.\n- Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.\n- Suggested actions must be in the form of a user instruction that you can follow.\n- Suggested actions could include actions that create artifacts.\n- After creating an artifact use a tool to add it to the chat context.\n\n## Context\n\nToday is {{DATETIME}}.\n";
391
+ // raw-loader:./system.tpl?raw
392
+ var system_default = "{{! System Prompt }}\n\nYou are a helpful assistant called Kai. \nYour name is Kai and you are powered by different language models.\nYou were created by DXOS and operate in Composer and on the DXOS EDGE network.\nIn your initial greeting state your name and make some suggestions based on the current context objects.\n\nYou are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\nYour task is to process user commands and questions and decide how best to respond.\nIn general be concise and direct.\n\nFollow these instructions carefully.\n\n## Include the following steps\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints\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## Context\n\nToday is {{DATETIME}}.\n";
393
393
 
394
394
  // src/templates/system.ts
395
395
  var createSystemPrompt = (options = {}) => Template.process(format_default, defaultsDeep(options, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/conversation/context.ts", "../../../src/conversation/conversation.ts", "../../../src/diff.ts", "../../../src/functions/services.ts", "../../../src/templates/system.ts", "raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw", "raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw", "../../../src/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ReadonlySignal, computed } from '@preact/signals-core';\nimport { Context, Schema } from 'effect';\nimport { Array, pipe } from 'effect';\n\nimport { Blueprint } from '@dxos/blueprints';\nimport { DXN, Obj, type Ref, type Relation, Type } from '@dxos/echo';\nimport { type Queue } from '@dxos/echo-db';\nimport { ComplexSet } from '@dxos/util';\n\n/**\n * Thread message that binds or unbinds contextual objects to a conversation.\n */\n// TODO(burdon): Move to @dxos/schema ContentBlock?\nexport const ContextBinding = Schema.Struct({\n blueprints: Schema.Struct({\n added: Schema.Array(Type.Ref(Blueprint.Blueprint)),\n removed: Schema.Array(Type.Ref(Blueprint.Blueprint)),\n }),\n\n // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)\n objects: Schema.Struct({\n added: Schema.Array(Type.Ref(Type.Expando)),\n removed: Schema.Array(Type.Ref(Type.Expando)),\n }),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/ContextBinding',\n version: '0.1.0',\n }),\n);\n\nexport interface ContextBinding extends Schema.Schema.Type<typeof ContextBinding> {}\n\nexport type BindingProps = Partial<{\n blueprints: Ref.Ref<Blueprint.Blueprint>[];\n objects: Ref.Ref<Type.Expando>[];\n}>;\n\nexport class Bindings {\n readonly blueprints = new ComplexSet<Ref.Ref<Blueprint.Blueprint>>((ref) => ref.dxn.toString());\n // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.\n readonly objects = new ComplexSet<Ref.Ref<Type.Expando>>((ref) => ref.dxn.asEchoDXN()?.echoId);\n\n toJSON() {\n return {\n blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),\n objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString()),\n };\n }\n}\n\n/**\n * Manages bindings of blueprints and objects to a conversation.\n */\n// TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?\nexport class AiContextBinder {\n /**\n * Reactive query of all bindings.\n */\n // TODO(burdon): Cache value?\n readonly bindings: ReadonlySignal<Bindings> = computed(() => this._reduce(this._queue.objects));\n\n readonly blueprints: ReadonlySignal<Ref.Ref<Blueprint.Blueprint>[]> = computed(() => [\n ...this.bindings.value.blueprints,\n ]);\n\n readonly objects: ReadonlySignal<Ref.Ref<Type.Expando>[]> = computed(() => [...this.bindings.value.objects]);\n\n constructor(private readonly _queue: Queue) {}\n\n /**\n * Asynchronous query of all bindings.\n */\n async query(): Promise<Bindings> {\n const queueItems = await this._queue.queryObjects();\n return this._reduce(queueItems);\n }\n\n // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.\n async bind(props: BindingProps): Promise<void> {\n if (!props.blueprints?.length && !props.objects?.length) {\n return;\n }\n\n const blueprints =\n props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ??\n [];\n const objects =\n props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];\n\n await this._queue.append([\n Obj.make(ContextBinding, {\n blueprints: {\n added: blueprints,\n removed: [],\n },\n objects: {\n added: objects,\n removed: [],\n },\n }),\n ]);\n }\n\n async unbind(props: BindingProps): Promise<void> {\n if (!props.blueprints?.length && !props.objects?.length) {\n return;\n }\n\n await this._queue.append([\n Obj.make(ContextBinding, {\n blueprints: {\n added: [],\n removed: props.blueprints ?? [],\n },\n objects: {\n added: [],\n removed: props.objects ?? [],\n },\n }),\n ]);\n }\n\n private _reduce(items: (Obj.Any | Relation.Any)[]): Bindings {\n return pipe(\n items,\n Array.filter(Obj.instanceOf(ContextBinding)),\n Array.reduce(new Bindings(), (context, item) => {\n item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));\n item.blueprints.added.forEach((ref) => context.blueprints.add(ref));\n item.objects.removed.forEach((ref) => {\n for (const obj of context.objects) {\n if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {\n context.objects.delete(obj);\n }\n }\n });\n item.objects.added.forEach((ref) => context.objects.add(ref));\n return context;\n }),\n );\n }\n}\n\nexport class AiContextService extends Context.Tag('@dxos/assistant/AiContextService')<\n AiContextService,\n {\n binder: AiContextBinder;\n }\n>() {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiTool, type AiToolkit } from '@effect/ai';\nimport { Array, Effect, Option } from 'effect';\n\nimport { Obj } from '@dxos/echo';\nimport { type Queue } from '@dxos/echo-db';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport {\n AiSession,\n type AiSessionRunError,\n type AiSessionRunRequirements,\n type GenerationObserver,\n createToolkit,\n} from '../session';\n\nimport { AiContextBinder, AiContextService, type ContextBinding } from './context';\n\nexport type AiConversationRunRequirements<Tools extends AiTool.Any> =\n | AiSessionRunRequirements\n | AiTool.ToHandler<Tools>;\n\nexport interface AiConversationRunParams {\n prompt: string;\n system?: string;\n observer?: GenerationObserver;\n}\n\nexport type AiConversationOptions = {\n queue: Queue<DataType.Message | ContextBinding>;\n};\n\n/**\n * Durable conversation state (initiated by users and agents) backed by a Queue.\n * Executes tools based on AI responses and supports cancellation of in-progress requests.\n */\nexport class AiConversation {\n /**\n * Message and binding queue.\n */\n private readonly _queue: Queue<DataType.Message | ContextBinding>;\n\n /**\n * Blueprints bound to the conversation.\n */\n private readonly _context: AiContextBinder;\n\n /**\n * Toolkit from the current session request.\n */\n private _toolkit: AiToolkit.ToHandler<AiTool.Any> | undefined;\n\n public constructor(options: AiConversationOptions) {\n this._queue = options.queue;\n this._context = new AiContextBinder(this._queue);\n }\n\n public get context() {\n return this._context;\n }\n\n public get toolkit() {\n return this._toolkit;\n }\n\n public async getHistory(): Promise<DataType.Message[]> {\n const queueItems = await this._queue.queryObjects();\n return queueItems.filter(Obj.instanceOf(DataType.Message));\n }\n\n /**\n * Creates a new cancelable request effect.\n */\n createRequest<Tools extends AiTool.Any>(\n params: AiConversationRunParams,\n ): Effect.Effect<DataType.Message[], AiSessionRunError, AiConversationRunRequirements<Tools>> {\n return Effect.gen(this, function* () {\n const session = new AiSession();\n const history = yield* Effect.promise(() => this.getHistory());\n\n // Get context objects.\n const context = yield* Effect.promise(() => this.context.query());\n const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(Array.map((option) => option.value)),\n );\n const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(Array.map((option) => option.value)),\n );\n\n // Create toolkit.\n const toolkit = yield* createToolkit<Tools>({ blueprints });\n this._toolkit = toolkit;\n\n const start = Date.now();\n log('run', {\n history: history.length,\n blueprints: blueprints.length,\n objects: objects.length,\n tools: this._toolkit?.tools.length ?? 0,\n });\n\n // Process request.\n const messages = yield* session.run<Tools>({ history, blueprints, objects, toolkit, ...params }).pipe(\n Effect.provideService(AiContextService, {\n binder: this.context,\n }),\n );\n\n log('result', { messages: messages.length, duration: Date.now() - start });\n\n // Append to queue.\n yield* Effect.promise(() => this._queue.append(messages));\n return messages;\n }).pipe(Effect.withSpan('AiConversation.request'));\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { next as A, type Doc } from '@automerge/automerge';\n\nimport { DocAccessor, toCursorRange } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\nimport { isNonNullable } from '@dxos/util';\n\n// Relevant info:\n// https://github.com/Minahil-official/GPT-4.1-Promting-Guide?tab=readme-ov-file#-apply-patch-tool-format-v4a-diff\n\n// TOOD(burdon): Support append to end (no \"-\").\n\nexport type Diff = {\n match: string;\n replace: string;\n};\n\n/**\n * Convert a list of diffs into a list of operations.\n */\nexport const reduceDiffs = (diffs: readonly string[]): Diff[] => {\n return diffs.reduce<Diff[]>((acc, diff) => {\n const current = acc[acc.length - 1];\n const [op, ...rest] = diff.split(' ');\n switch (op) {\n case '-': {\n if (current && !current.match) {\n current.match += rest.join(' ');\n } else {\n acc.push({ match: rest.join(' '), replace: '' });\n }\n return acc;\n }\n case '+': {\n if (current && !current.replace) {\n current.replace += rest.join(' ');\n } else {\n acc.push({ match: '', replace: rest.join(' ') });\n }\n return acc;\n }\n }\n\n return acc;\n }, []);\n};\n\nexport const computeDiffsWithCursors = <T>(accessor: DocAccessor<T>, diffs: readonly string[]) => {\n return reduceDiffs(diffs)\n .map((diff) => {\n const text = DocAccessor.getValue<string>(accessor);\n const idx = text.indexOf(diff.match);\n if (idx !== -1) {\n return { cursor: toCursorRange(accessor, idx, idx + diff.match.length), text: diff.replace };\n }\n })\n .filter(isNonNullable);\n};\n\nexport const applyDiffs = <T>(accessor: DocAccessor<T>, diffs: readonly string[]): string => {\n for (const diff of reduceDiffs(diffs)) {\n accessor.handle.change((doc: Doc<T>) => {\n const text = DocAccessor.getValue<string>(accessor);\n const idx = text.indexOf(diff.match);\n if (idx !== -1) {\n // TODO(burdon): Replace smallest substring.\n // NOTE: This only replaces the first match.\n A.splice(doc, accessor.path as A.Prop[], idx, diff.match.length, diff.replace);\n } else {\n log.warn('diff not found', diff);\n }\n });\n }\n\n return DocAccessor.getValue<string>(accessor);\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { AiTool, type AiToolkit } from '@effect/ai';\nimport { Context, Effect, Layer, Record, Schema } from 'effect';\n\nimport { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';\nimport { todo } from '@dxos/debug';\nimport { type FunctionDefinition, LocalFunctionExecutionService } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\n\nexport const makeToolResolverFromFunctions = (\n functions: FunctionDefinition<any, any>[],\n toolkit: AiToolkit.Any,\n): Layer.Layer<ToolResolverService> => {\n return Layer.succeed(ToolResolverService, {\n resolve: Effect.fn('resolveTool')(function* (id) {\n const tool = toolkit.tools[id];\n if (tool) {\n return tool;\n }\n\n const functionDef = functions.find((fn) => fn.name === id);\n if (!functionDef) {\n return yield* Effect.fail(new AiToolNotFoundError(id));\n }\n\n return projectFunctionToTool(functionDef);\n }),\n });\n};\n\nexport const makeToolExecutionServiceFromFunctions = (\n functions: FunctionDefinition<any, any>[],\n toolkit: AiToolkit.AiToolkit<AiTool.Any>,\n handlersLayer: Layer.Layer<AiTool.ToHandler<AiTool.AiTool<any>>, never, never>,\n): Layer.Layer<ToolExecutionService, never, LocalFunctionExecutionService> => {\n return Layer.effect(\n ToolExecutionService,\n Effect.gen(function* () {\n const toolkitHandler = yield* toolkit.pipe(Effect.provide(handlersLayer));\n const localFunctionExecutionService = yield* LocalFunctionExecutionService;\n\n return {\n handlersFor: (toolkit) => {\n const makeHandler = (tool: AiTool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {\n return Effect.fn('toolFunctionHandler')(function* (input: any) {\n if (toolkitHandler.tools.find((t: AiTool.Any) => t.name === tool.name)) {\n // TODO(wittjosiah): Everything is `never` here.\n return yield* (toolkitHandler.handle as any)(tool.name, input);\n }\n\n const { functionName } = Context.get(FunctionToolAnnotation)(tool.annotations as any);\n const functionDef = functions.find((fn) => fn.name === functionName);\n if (!functionDef) {\n return yield* Effect.fail(new AiToolNotFoundError(tool.name));\n }\n\n return yield* localFunctionExecutionService\n .invokeFunction(functionDef, input)\n .pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));\n });\n };\n\n return toolkit.of(Record.map(toolkit.tools, (tool, _name) => makeHandler(tool)) as any) as any;\n },\n };\n }),\n );\n};\n\n/**\n * Tools that are projected from functions have this annotation.\n */\nclass FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAnnotation')<\n FunctionToolAnnotation,\n {\n functionName: string;\n }\n>() {}\n\nconst toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();\n\nconst projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {\n if (toolCache.has(fn)) {\n return toolCache.get(fn)!;\n }\n\n const tool = AiTool.make(makeToolName(fn.name), {\n description: fn.description,\n parameters: createStructFieldsFromSchema(fn.inputSchema),\n // TODO(dmaretskyi): Include output schema.\n failure: Schema.Any, // TODO(dmaretskyi): Better type for the failure?\n }).annotate(FunctionToolAnnotation, { functionName: fn.name });\n toolCache.set(fn, tool);\n return tool;\n};\n\n/**\n * @returns Tool name produced from function name by escaping invalid characters.\n */\nconst makeToolName = (name: string) => {\n const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');\n invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));\n return toolName;\n};\n\n// TODO(dmaretskyi): Factor out.\nconst createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {\n switch (schema.ast._tag) {\n case 'TypeLiteral':\n return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));\n case 'VoidKeyword':\n return {};\n default:\n return todo(`Unsupported schema AST: ${schema.ast._tag}`);\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport defaultsDeep from 'lodash.defaultsdeep';\n\nimport { type ModelCapabilities } from '@dxos/ai';\nimport { Template } from '@dxos/blueprints';\n\nimport FORMAT from './format.tpl?raw';\nimport SYSTEM from './system.tpl?raw';\n\n/**\n * System template variables.\n */\nexport type SystemPromptOptions = ModelCapabilities & {\n DATETIME: string;\n};\n\n/**\n * Base system prompt.\n * NOTE: This contains protocol instructions that can not be dynamically edited.\n */\nexport const createSystemPrompt = (options: Partial<SystemPromptOptions> = {}) =>\n Template.process<SystemPromptOptions>(\n FORMAT,\n defaultsDeep(options, {\n DATETIME: new Date().toISOString(),\n }),\n );\n\nexport const templates = {\n /** Editable system prompt.*/\n system: Template.make({\n /**\n * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.\n */\n id: '01K2J2FZWH39F55CS7B26GP1Q3',\n source: SYSTEM,\n }),\n};\n", "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\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## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n", "{{! System Prompt }}\n\n- You are a helpful assistant called Kai. \n- Your name is Kai and you are powered by different language models.\n- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.\n- In your initial greeting state your name and make some suggestions based on the current context objects.\n- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\n- Your task is to process user commands and questions and decide how best to respond.\n- In general be concise and direct.\n- Follow all instructions carefully.\n\n## Planning\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints and Artifacts\n\n- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.\n- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.\n- If it is ambiguous, query for existing artifacts first and then decide.\n- If you decide to create an artifact, call the associated tool to create the artifact.\n- Artifacts are stored in the database. Tools are used to create and query artifacts.\n- If you are unsure about creating an artifact ask the user for clarification.\n- Artifacts are mutable objects that can change over the course of the conversation.\n- Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.\n- You must never generate the id of the artifact; only recall the ids that are already in the history.\n- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.\n- You can add suggested actions at the end of your response.\n- Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.\n- Suggested actions must be in the form of a user instruction that you can follow.\n- Suggested actions could include actions that create artifacts.\n- After creating an artifact use a tool to add it to the chat context.\n\n## Context\n\nToday is {{DATETIME}}.\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type ObjectId } from '@dxos/echo-schema';\nimport { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';\nimport { trim } from '@dxos/util';\n\n/**\n * @deprecated\n */\nexport const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;\n\n/**\n * A model-friendly way to reference an object.\n * Supports vairous formats that will be normalized to a DXN.\n */\n// TODO(burdon): Rename ObjectReference?\nexport const ArtifactId: Schema.Schema<string> & {\n toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;\n} = class extends Schema.String.annotations({\n description: trim`\n The ID of the referenced object. Formats accepted:\n - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.\n - space ID, object ID tuple (spaceID:objectID)\n - Only object ID that is assumed to be in the current space (XXXXX)\n `,\n examples: ['dxn:echo:@:XXXXX', '@dxn:echo:@:XXXXX', 'spaceID:objectID', 'XXXXX'],\n}) {\n static toDXN(reference: ArtifactId, owningSpaceId?: SpaceId): DXN {\n // Allow @dxn: prefix for compatibility with in-text references.\n if (reference.startsWith('@dxn:')) {\n return DXN.parse(reference.slice(1));\n } else if (reference.startsWith('dxn:')) {\n return DXN.parse(reference);\n } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {\n const [spaceId, objectId] = reference.split(':');\n // This is a workaround because the current Filter API doesn't work with fully qualified Echo DXNs.\n // We check if the space ID is the same as the owning space and then use LOCAL_SPACE_TAG for local references.\n // TODO(dmaretskyi): Fix this in the Echo and Filter API to properly handle fully qualified DXNs.\n return new DXN(DXN.kind.ECHO, [spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId, objectId]);\n } else if (/^[A-Z0-9]+$/.test(reference)) {\n return DXN.fromLocalObjectId(reference);\n } else {\n throw new Error(`Unable to parse object reference: ${reference}`);\n }\n }\n};\n\nexport type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;\n"],
3
+ "sources": ["../../../src/conversation/context.ts", "../../../src/conversation/conversation.ts", "../../../src/diff.ts", "../../../src/functions/services.ts", "../../../src/templates/system.ts", "raw-loader:./format.tpl?raw", "raw-loader:./system.tpl?raw", "../../../src/types.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ReadonlySignal, computed } from '@preact/signals-core';\nimport { Context, Schema } from 'effect';\nimport { Array, pipe } from 'effect';\n\nimport { Blueprint } from '@dxos/blueprints';\nimport { DXN, Obj, type Ref, type Relation, Type } from '@dxos/echo';\nimport { type Queue } from '@dxos/echo-db';\nimport { ComplexSet } from '@dxos/util';\n\n/**\n * Thread message that binds or unbinds contextual objects to a conversation.\n */\n// TODO(burdon): Move to @dxos/schema ContentBlock?\nexport const ContextBinding = Schema.Struct({\n blueprints: Schema.Struct({\n added: Schema.Array(Type.Ref(Blueprint.Blueprint)),\n removed: Schema.Array(Type.Ref(Blueprint.Blueprint)),\n }),\n\n // TODO(burdon): Type.Expando => Type.Obj (or Obj.Any?)\n objects: Schema.Struct({\n added: Schema.Array(Type.Ref(Type.Expando)),\n removed: Schema.Array(Type.Ref(Type.Expando)),\n }),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/ContextBinding',\n version: '0.1.0',\n }),\n);\n\nexport interface ContextBinding extends Schema.Schema.Type<typeof ContextBinding> {}\n\nexport type BindingProps = Partial<{\n blueprints: Ref.Ref<Blueprint.Blueprint>[];\n objects: Ref.Ref<Type.Expando>[];\n}>;\n\nexport class Bindings {\n readonly blueprints = new ComplexSet<Ref.Ref<Blueprint.Blueprint>>((ref) => ref.dxn.toString());\n // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.\n readonly objects = new ComplexSet<Ref.Ref<Type.Expando>>((ref) => ref.dxn.asEchoDXN()?.echoId);\n\n toJSON() {\n return {\n blueprints: Array.fromIterable(this.blueprints).map((ref) => ref.dxn.toString()),\n objects: Array.fromIterable(this.objects).map((ref) => ref.dxn.toString()),\n };\n }\n}\n\n/**\n * Manages bindings of blueprints and objects to a conversation.\n */\n// TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?\nexport class AiContextBinder {\n /**\n * Reactive query of all bindings.\n */\n // TODO(burdon): Cache value?\n readonly bindings: ReadonlySignal<Bindings> = computed(() => this._reduce(this._queue.objects));\n\n readonly blueprints: ReadonlySignal<Ref.Ref<Blueprint.Blueprint>[]> = computed(() => [\n ...this.bindings.value.blueprints,\n ]);\n\n readonly objects: ReadonlySignal<Ref.Ref<Type.Expando>[]> = computed(() => [...this.bindings.value.objects]);\n\n constructor(private readonly _queue: Queue) {}\n\n /**\n * Asynchronous query of all bindings.\n */\n async query(): Promise<Bindings> {\n const queueItems = await this._queue.queryObjects();\n return this._reduce(queueItems);\n }\n\n // TODO(burdon): Pass in Blueprint obj (from registry?) and create reference.\n async bind(props: BindingProps): Promise<void> {\n if (!props.blueprints?.length && !props.objects?.length) {\n return;\n }\n\n const blueprints =\n props.blueprints?.filter((ref) => !this.blueprints.peek().find((b) => b.dxn.toString() === ref.dxn.toString())) ??\n [];\n const objects =\n props.objects?.filter((ref) => !this.objects.peek().find((o) => o.dxn.toString() === ref.dxn.toString())) ?? [];\n\n await this._queue.append([\n Obj.make(ContextBinding, {\n blueprints: {\n added: blueprints,\n removed: [],\n },\n objects: {\n added: objects,\n removed: [],\n },\n }),\n ]);\n }\n\n async unbind(props: BindingProps): Promise<void> {\n if (!props.blueprints?.length && !props.objects?.length) {\n return;\n }\n\n await this._queue.append([\n Obj.make(ContextBinding, {\n blueprints: {\n added: [],\n removed: props.blueprints ?? [],\n },\n objects: {\n added: [],\n removed: props.objects ?? [],\n },\n }),\n ]);\n }\n\n private _reduce(items: (Obj.Any | Relation.Any)[]): Bindings {\n return pipe(\n items,\n Array.filter(Obj.instanceOf(ContextBinding)),\n Array.reduce(new Bindings(), (context, item) => {\n item.blueprints.removed.forEach((ref) => context.blueprints.delete(ref));\n item.blueprints.added.forEach((ref) => context.blueprints.add(ref));\n item.objects.removed.forEach((ref) => {\n for (const obj of context.objects) {\n if (DXN.equalsEchoId(obj.dxn, ref.dxn)) {\n context.objects.delete(obj);\n }\n }\n });\n item.objects.added.forEach((ref) => context.objects.add(ref));\n return context;\n }),\n );\n }\n}\n\nexport class AiContextService extends Context.Tag('@dxos/assistant/AiContextService')<\n AiContextService,\n {\n binder: AiContextBinder;\n }\n>() {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AiTool, type AiToolkit } from '@effect/ai';\nimport { Array, Effect, Option } from 'effect';\n\nimport { Obj } from '@dxos/echo';\nimport { type Queue } from '@dxos/echo-db';\nimport { DatabaseService } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport {\n AiSession,\n type AiSessionRunError,\n type AiSessionRunRequirements,\n type GenerationObserver,\n createToolkit,\n} from '../session';\n\nimport { AiContextBinder, AiContextService, type ContextBinding } from './context';\n\nexport type AiConversationRunRequirements<Tools extends AiTool.Any> =\n | AiSessionRunRequirements\n | AiTool.ToHandler<Tools>;\n\nexport interface AiConversationRunParams {\n prompt: string;\n system?: string;\n observer?: GenerationObserver;\n}\n\nexport type AiConversationOptions = {\n queue: Queue<DataType.Message | ContextBinding>;\n};\n\n/**\n * Durable conversation state (initiated by users and agents) backed by a Queue.\n * Executes tools based on AI responses and supports cancellation of in-progress requests.\n */\nexport class AiConversation {\n /**\n * Message and binding queue.\n */\n private readonly _queue: Queue<DataType.Message | ContextBinding>;\n\n /**\n * Blueprints bound to the conversation.\n */\n private readonly _context: AiContextBinder;\n\n /**\n * Toolkit from the current session request.\n */\n private _toolkit: AiToolkit.ToHandler<AiTool.Any> | undefined;\n\n public constructor(options: AiConversationOptions) {\n this._queue = options.queue;\n this._context = new AiContextBinder(this._queue);\n }\n\n public get context() {\n return this._context;\n }\n\n public get toolkit() {\n return this._toolkit;\n }\n\n public async getHistory(): Promise<DataType.Message[]> {\n const queueItems = await this._queue.queryObjects();\n return queueItems.filter(Obj.instanceOf(DataType.Message));\n }\n\n /**\n * Creates a new cancelable request effect.\n */\n createRequest<Tools extends AiTool.Any>(\n params: AiConversationRunParams,\n ): Effect.Effect<DataType.Message[], AiSessionRunError, AiConversationRunRequirements<Tools>> {\n return Effect.gen(this, function* () {\n const session = new AiSession();\n const history = yield* Effect.promise(() => this.getHistory());\n\n // Get context objects.\n const context = yield* Effect.promise(() => this.context.query());\n const blueprints = yield* Effect.forEach(context.blueprints.values(), DatabaseService.loadOption).pipe(\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(Array.map((option) => option.value)),\n );\n const objects = yield* Effect.forEach(context.objects.values(), DatabaseService.loadOption).pipe(\n Effect.map(Array.filter(Option.isSome)),\n Effect.map(Array.map((option) => option.value)),\n );\n\n // Create toolkit.\n const toolkit = yield* createToolkit<Tools>({ blueprints });\n this._toolkit = toolkit;\n\n const start = Date.now();\n log('run', {\n history: history.length,\n blueprints: blueprints.length,\n objects: objects.length,\n tools: this._toolkit?.tools.length ?? 0,\n });\n\n // Process request.\n const messages = yield* session.run<Tools>({ history, blueprints, objects, toolkit, ...params }).pipe(\n Effect.provideService(AiContextService, {\n binder: this.context,\n }),\n );\n\n log('result', { messages: messages.length, duration: Date.now() - start });\n\n // Append to queue.\n yield* Effect.promise(() => this._queue.append(messages));\n return messages;\n }).pipe(Effect.withSpan('AiConversation.request'));\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { next as A, type Doc } from '@automerge/automerge';\n\nimport { DocAccessor, toCursorRange } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\nimport { isNonNullable } from '@dxos/util';\n\n// Relevant info:\n// https://github.com/Minahil-official/GPT-4.1-Promting-Guide?tab=readme-ov-file#-apply-patch-tool-format-v4a-diff\n\n// TOOD(burdon): Support append to end (no \"-\").\n\nexport type Diff = {\n match: string;\n replace: string;\n};\n\n/**\n * Convert a list of diffs into a list of operations.\n */\nexport const reduceDiffs = (diffs: readonly string[]): Diff[] => {\n return diffs.reduce<Diff[]>((acc, diff) => {\n const current = acc[acc.length - 1];\n const [op, ...rest] = diff.split(' ');\n switch (op) {\n case '-': {\n if (current && !current.match) {\n current.match += rest.join(' ');\n } else {\n acc.push({ match: rest.join(' '), replace: '' });\n }\n return acc;\n }\n case '+': {\n if (current && !current.replace) {\n current.replace += rest.join(' ');\n } else {\n acc.push({ match: '', replace: rest.join(' ') });\n }\n return acc;\n }\n }\n\n return acc;\n }, []);\n};\n\nexport const computeDiffsWithCursors = <T>(accessor: DocAccessor<T>, diffs: readonly string[]) => {\n return reduceDiffs(diffs)\n .map((diff) => {\n const text = DocAccessor.getValue<string>(accessor);\n const idx = text.indexOf(diff.match);\n if (idx !== -1) {\n return { cursor: toCursorRange(accessor, idx, idx + diff.match.length), text: diff.replace };\n }\n })\n .filter(isNonNullable);\n};\n\nexport const applyDiffs = <T>(accessor: DocAccessor<T>, diffs: readonly string[]): string => {\n for (const diff of reduceDiffs(diffs)) {\n accessor.handle.change((doc: Doc<T>) => {\n const text = DocAccessor.getValue<string>(accessor);\n const idx = text.indexOf(diff.match);\n if (idx !== -1) {\n // TODO(burdon): Replace smallest substring.\n // NOTE: This only replaces the first match.\n A.splice(doc, accessor.path as A.Prop[], idx, diff.match.length, diff.replace);\n } else {\n log.warn('diff not found', diff);\n }\n });\n }\n\n return DocAccessor.getValue<string>(accessor);\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { AiTool, type AiToolkit } from '@effect/ai';\nimport { Context, Effect, Layer, Record, Schema } from 'effect';\n\nimport { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';\nimport { todo } from '@dxos/debug';\nimport { type FunctionDefinition, LocalFunctionExecutionService } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\n\nexport const makeToolResolverFromFunctions = (\n functions: FunctionDefinition<any, any>[],\n toolkit: AiToolkit.Any,\n): Layer.Layer<ToolResolverService> => {\n return Layer.succeed(ToolResolverService, {\n resolve: Effect.fn('resolveTool')(function* (id) {\n const tool = toolkit.tools[id];\n if (tool) {\n return tool;\n }\n\n const functionDef = functions.find((fn) => fn.name === id);\n if (!functionDef) {\n return yield* Effect.fail(new AiToolNotFoundError(id));\n }\n\n return projectFunctionToTool(functionDef);\n }),\n });\n};\n\nexport const makeToolExecutionServiceFromFunctions = (\n functions: FunctionDefinition<any, any>[],\n toolkit: AiToolkit.AiToolkit<AiTool.Any>,\n handlersLayer: Layer.Layer<AiTool.ToHandler<AiTool.AiTool<any>>, never, never>,\n): Layer.Layer<ToolExecutionService, never, LocalFunctionExecutionService> => {\n return Layer.effect(\n ToolExecutionService,\n Effect.gen(function* () {\n const toolkitHandler = yield* toolkit.pipe(Effect.provide(handlersLayer));\n const localFunctionExecutionService = yield* LocalFunctionExecutionService;\n\n return {\n handlersFor: (toolkit) => {\n const makeHandler = (tool: AiTool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {\n return Effect.fn('toolFunctionHandler')(function* (input: any) {\n if (toolkitHandler.tools.find((t: AiTool.Any) => t.name === tool.name)) {\n // TODO(wittjosiah): Everything is `never` here.\n return yield* (toolkitHandler.handle as any)(tool.name, input);\n }\n\n const { functionName } = Context.get(FunctionToolAnnotation)(tool.annotations as any);\n const functionDef = functions.find((fn) => fn.name === functionName);\n if (!functionDef) {\n return yield* Effect.fail(new AiToolNotFoundError(tool.name));\n }\n\n return yield* localFunctionExecutionService\n .invokeFunction(functionDef, input)\n .pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));\n });\n };\n\n return toolkit.of(Record.map(toolkit.tools, (tool, _name) => makeHandler(tool)) as any) as any;\n },\n };\n }),\n );\n};\n\n/**\n * Tools that are projected from functions have this annotation.\n */\nclass FunctionToolAnnotation extends Context.Tag('@dxos/assisatnt/FunctionToolAnnotation')<\n FunctionToolAnnotation,\n {\n functionName: string;\n }\n>() {}\n\nconst toolCache = new WeakMap<FunctionDefinition<any, any>, AiTool.Any>();\n\nconst projectFunctionToTool = (fn: FunctionDefinition<any, any>): AiTool.Any => {\n if (toolCache.has(fn)) {\n return toolCache.get(fn)!;\n }\n\n const tool = AiTool.make(makeToolName(fn.name), {\n description: fn.description,\n parameters: createStructFieldsFromSchema(fn.inputSchema),\n // TODO(dmaretskyi): Include output schema.\n failure: Schema.Any, // TODO(dmaretskyi): Better type for the failure?\n }).annotate(FunctionToolAnnotation, { functionName: fn.name });\n toolCache.set(fn, tool);\n return tool;\n};\n\n/**\n * @returns Tool name produced from function name by escaping invalid characters.\n */\nconst makeToolName = (name: string) => {\n const toolName = name.replace(/[^a-zA-Z0-9]/g, '_');\n invariant(toolName.match(/^[a-zA-Z_][a-zA-Z0-9-_]*$/));\n return toolName;\n};\n\n// TODO(dmaretskyi): Factor out.\nconst createStructFieldsFromSchema = (schema: Schema.Schema<any, any>): Record<string, Schema.Schema<any, any>> => {\n switch (schema.ast._tag) {\n case 'TypeLiteral':\n return Object.fromEntries(schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(prop.type)]));\n case 'VoidKeyword':\n return {};\n default:\n return todo(`Unsupported schema AST: ${schema.ast._tag}`);\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport defaultsDeep from 'lodash.defaultsdeep';\n\nimport { type ModelCapabilities } from '@dxos/ai';\nimport { Template } from '@dxos/blueprints';\n\nimport FORMAT from './format.tpl?raw';\nimport SYSTEM from './system.tpl?raw';\n\n/**\n * System template variables.\n */\nexport type SystemPromptOptions = ModelCapabilities & {\n DATETIME: string;\n};\n\n/**\n * Base system prompt.\n * NOTE: This contains protocol instructions that can not be dynamically edited.\n */\nexport const createSystemPrompt = (options: Partial<SystemPromptOptions> = {}) =>\n Template.process<SystemPromptOptions>(\n FORMAT,\n defaultsDeep(options, {\n DATETIME: new Date().toISOString(),\n }),\n );\n\nexport const templates = {\n /** Editable system prompt.*/\n system: Template.make({\n /**\n * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.\n */\n id: '01K2J2FZWH39F55CS7B26GP1Q3',\n source: SYSTEM,\n }),\n};\n", "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\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## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n", "{{! System Prompt }}\n\nYou are a helpful assistant called Kai. \nYour name is Kai and you are powered by different language models.\nYou were created by DXOS and operate in Composer and on the DXOS EDGE network.\nIn your initial greeting state your name and make some suggestions based on the current context objects.\n\nYou are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\nYour task is to process user commands and questions and decide how best to respond.\nIn general be concise and direct.\n\nFollow these instructions carefully.\n\n## Include the following steps\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints\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## Context\n\nToday is {{DATETIME}}.\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type ObjectId } from '@dxos/echo-schema';\nimport { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';\nimport { trim } from '@dxos/util';\n\n/**\n * @deprecated\n */\nexport const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;\n\n/**\n * A model-friendly way to reference an object.\n * Supports vairous formats that will be normalized to a DXN.\n */\n// TODO(burdon): Rename ObjectReference?\nexport const ArtifactId: Schema.Schema<string> & {\n toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;\n} = class extends Schema.String.annotations({\n description: trim`\n The ID of the referenced object. Formats accepted:\n - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.\n - space ID, object ID tuple (spaceID:objectID)\n - Only object ID that is assumed to be in the current space (XXXXX)\n `,\n examples: ['dxn:echo:@:XXXXX', '@dxn:echo:@:XXXXX', 'spaceID:objectID', 'XXXXX'],\n}) {\n static toDXN(reference: ArtifactId, owningSpaceId?: SpaceId): DXN {\n // Allow @dxn: prefix for compatibility with in-text references.\n if (reference.startsWith('@dxn:')) {\n return DXN.parse(reference.slice(1));\n } else if (reference.startsWith('dxn:')) {\n return DXN.parse(reference);\n } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {\n const [spaceId, objectId] = reference.split(':');\n // This is a workaround because the current Filter API doesn't work with fully qualified Echo DXNs.\n // We check if the space ID is the same as the owning space and then use LOCAL_SPACE_TAG for local references.\n // TODO(dmaretskyi): Fix this in the Echo and Filter API to properly handle fully qualified DXNs.\n return new DXN(DXN.kind.ECHO, [spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId, objectId]);\n } else if (/^[A-Z0-9]+$/.test(reference)) {\n return DXN.fromLocalObjectId(reference);\n } else {\n throw new Error(`Unable to parse object reference: ${reference}`);\n }\n }\n};\n\nexport type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;\n"],
5
5
  "mappings": ";;;;;;;;;;;AAIA,SAA8BA,gBAAgB;AAC9C,SAASC,SAASC,cAAc;AAChC,SAASC,OAAOC,YAAY;AAE5B,SAASC,iBAAiB;AAC1B,SAASC,KAAKC,KAA8BC,YAAY;AAExD,SAASC,kBAAkB;;;;;;;;;;;;;;AAMpB,IAAMC,iBAAiBC,OAAOC,O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,MAAKC,uBAAqC;AACnD,SAASC,YAAY;AAKd,IAAMC,wBAAwB,CAACC,OAAiB,gBAAgBA,EAAAA;AAOhE,IAAMC,aAET,cAAcC,QAAOC,OAAOC,YAAY;EAC1CC,aAAaC;;;;;;EAMbC,UAAU;IAAC;IAAoB;IAAqB;IAAoB;;AAC1E,CAAA,EAAA;EACE,OAAOC,MAAMC,WAAuBC,eAA8B;AAEhE,QAAID,UAAUE,WAAW,OAAA,GAAU;AACjC,aAAOC,KAAIC,MAAMJ,UAAUK,MAAM,CAAA,CAAA;IACnC,WAAWL,UAAUE,WAAW,MAAA,GAAS;AACvC,aAAOC,KAAIC,MAAMJ,SAAAA;IACnB,WAAW,wBAAwBM,KAAKN,SAAAA,GAAY;AAClD,YAAM,CAACO,SAASC,QAAAA,IAAYR,UAAUS,MAAM,GAAA;AAI5C,aAAO,IAAIN,KAAIA,KAAIO,KAAKC,MAAM;QAACJ,YAAYN,gBAAgBW,kBAAkBL;QAASC;OAAS;IACjG,WAAW,cAAcF,KAAKN,SAAAA,GAAY;AACxC,aAAOG,KAAIU,kBAAkBb,SAAAA;IAC/B,OAAO;AACL,YAAM,IAAIc,MAAM,qCAAqCd,SAAAA,EAAW;IAClE;EACF;AACF;",
6
6
  "names": ["computed", "Context", "Schema", "Array", "pipe", "Blueprint", "DXN", "Obj", "Type", "ComplexSet", "ContextBinding", "Schema", "Struct", "blueprints", "added", "Array", "Type", "Ref", "Blueprint", "removed", "objects", "Expando", "pipe", "Obj", "typename", "version", "Bindings", "toJSON", "fromIterable", "map", "ref", "dxn", "toString", "ComplexSet", "asEchoDXN", "echoId", "AiContextBinder", "query", "queueItems", "_queue", "queryObjects", "_reduce", "bind", "props", "length", "filter", "peek", "find", "b", "o", "append", "make", "unbind", "items", "instanceOf", "reduce", "context", "item", "forEach", "delete", "add", "obj", "DXN", "equalsEchoId", "bindings", "computed", "value", "AiContextService", "Context", "Tag", "Array", "Effect", "Option", "Obj", "DatabaseService", "log", "DataType", "AiConversation", "context", "_context", "toolkit", "_toolkit", "getHistory", "queueItems", "_queue", "queryObjects", "filter", "Obj", "instanceOf", "DataType", "Message", "createRequest", "params", "Effect", "gen", "session", "AiSession", "history", "promise", "query", "blueprints", "forEach", "values", "DatabaseService", "loadOption", "pipe", "map", "Array", "Option", "isSome", "option", "value", "objects", "createToolkit", "start", "Date", "now", "log", "length", "tools", "messages", "run", "provideService", "AiContextService", "binder", "duration", "append", "withSpan", "options", "_define_property", "queue", "AiContextBinder", "next", "A", "DocAccessor", "toCursorRange", "log", "isNonNullable", "reduceDiffs", "diffs", "reduce", "acc", "diff", "current", "length", "op", "rest", "split", "match", "join", "push", "replace", "computeDiffsWithCursors", "accessor", "map", "text", "getValue", "idx", "indexOf", "cursor", "filter", "applyDiffs", "handle", "change", "doc", "splice", "path", "warn", "AiTool", "Context", "Effect", "Layer", "Record", "Schema", "AiToolNotFoundError", "ToolExecutionService", "ToolResolverService", "todo", "LocalFunctionExecutionService", "invariant", "makeToolResolverFromFunctions", "functions", "toolkit", "succeed", "resolve", "fn", "id", "tool", "tools", "functionDef", "find", "name", "fail", "projectFunctionToTool", "makeToolExecutionServiceFromFunctions", "handlersLayer", "effect", "gen", "toolkitHandler", "pipe", "provide", "localFunctionExecutionService", "handlersFor", "makeHandler", "input", "t", "handle", "functionName", "get", "FunctionToolAnnotation", "annotations", "invokeFunction", "catchAllDefect", "defect", "of", "map", "_name", "Tag", "toolCache", "WeakMap", "has", "make", "makeToolName", "description", "parameters", "createStructFieldsFromSchema", "inputSchema", "failure", "Any", "annotate", "set", "toolName", "replace", "match", "schema", "ast", "_tag", "Object", "fromEntries", "propertySignatures", "prop", "type", "defaultsDeep", "Template", "createSystemPrompt", "options", "Template", "process", "FORMAT", "defaultsDeep", "DATETIME", "Date", "toISOString", "templates", "system", "make", "id", "source", "SYSTEM", "Schema", "DXN", "LOCAL_SPACE_TAG", "trim", "createArtifactElement", "id", "ArtifactId", "Schema", "String", "annotations", "description", "trim", "examples", "toDXN", "reference", "owningSpaceId", "startsWith", "DXN", "parse", "slice", "test", "spaceId", "objectId", "split", "kind", "ECHO", "LOCAL_SPACE_TAG", "fromLocalObjectId", "Error"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"src/conversation/context.ts":{"bytes":16750,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/session/artifact-diff.ts":{"bytes":2575,"imports":[{"path":"effect","kind":"import-statement","external":true}],"format":"esm"},"src/session/observer.ts":{"bytes":5294,"imports":[{"path":"effect","kind":"import-statement","external":true}],"format":"esm"},"src/errors.ts":{"bytes":1420,"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true}],"format":"esm"},"src/session/error-handling.ts":{"bytes":4851,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"@effect/platform","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"../errors"}],"format":"esm"},"src/session/format.ts":{"bytes":16676,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"../errors"},{"path":"src/session/artifact-diff.ts","kind":"import-statement","original":"./artifact-diff"}],"format":"esm"},"src/session/session.ts":{"bytes":22852,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/session/error-handling.ts","kind":"import-statement","original":"./error-handling"},{"path":"src/session/format.ts","kind":"import-statement","original":"./format"},{"path":"src/session/observer.ts","kind":"import-statement","original":"./observer"}],"format":"esm"},"src/session/toolkit.ts":{"bytes":4171,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/session/version-pin.ts":{"bytes":4556,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"format":"esm"},"src/session/index.ts":{"bytes":832,"imports":[{"path":"src/session/artifact-diff.ts","kind":"import-statement","original":"./artifact-diff"},{"path":"src/session/observer.ts","kind":"import-statement","original":"./observer"},{"path":"src/session/session.ts","kind":"import-statement","original":"./session"},{"path":"src/session/toolkit.ts","kind":"import-statement","original":"./toolkit"},{"path":"src/session/version-pin.ts","kind":"import-statement","original":"./version-pin"}],"format":"esm"},"src/conversation/conversation.ts":{"bytes":12652,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/session/index.ts","kind":"import-statement","original":"../session"},{"path":"src/conversation/context.ts","kind":"import-statement","original":"./context"}],"format":"esm"},"src/conversation/index.ts":{"bytes":562,"imports":[{"path":"src/conversation/context.ts","kind":"import-statement","original":"./context"},{"path":"src/conversation/conversation.ts","kind":"import-statement","original":"./conversation"}],"format":"esm"},"src/diff.ts":{"bytes":8472,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/functions/services.ts":{"bytes":14583,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"src/functions/index.ts":{"bytes":460,"imports":[{"path":"src/functions/services.ts","kind":"import-statement","original":"./services"}],"format":"esm"},"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw":{"bytes":1915,"imports":[]},"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw":{"bytes":3351,"imports":[]},"src/templates/system.ts":{"bytes":3127,"imports":[{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw","kind":"import-statement","original":"./format.tpl?raw"},{"path":"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw","kind":"import-statement","original":"./system.tpl?raw"}],"format":"esm"},"src/templates/index.ts":{"bytes":458,"imports":[{"path":"src/templates/system.ts","kind":"import-statement","original":"./system"}],"format":"esm"},"src/types.ts":{"bytes":6867,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":974,"imports":[{"path":"src/conversation/index.ts","kind":"import-statement","original":"./conversation"},{"path":"src/diff.ts","kind":"import-statement","original":"./diff"},{"path":"src/functions/index.ts","kind":"import-statement","original":"./functions"},{"path":"src/session/index.ts","kind":"import-statement","original":"./session"},{"path":"src/templates/index.ts","kind":"import-statement","original":"./templates"},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"src/extraction/extraction.ts":{"bytes":6822,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true}],"format":"esm"},"src/extraction/quotes.ts":{"bytes":7110,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw":{"bytes":1318,"imports":[]},"src/extraction/extraction-llm-function/extraction-llm-function.ts":{"bytes":8479,"imports":[{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/session/index.ts","kind":"import-statement","original":"../../session"},{"path":"src/extraction/extraction.ts","kind":"import-statement","original":"../extraction"},{"path":"src/extraction/quotes.ts","kind":"import-statement","original":"../quotes"},{"path":"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw","kind":"import-statement","original":"./instructions.tpl?raw"}],"format":"esm"},"src/extraction/extraction-llm-function/index.ts":{"bytes":524,"imports":[{"path":"src/extraction/extraction-llm-function/extraction-llm-function.ts","kind":"import-statement","original":"./extraction-llm-function"}],"format":"esm"},"src/extraction/extraction-ner-function/named-entity-recognition.ts":{"bytes":10067,"imports":[{"path":"@xenova/transformers","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/extraction/extraction-ner-function/extraction-ner-function.ts":{"bytes":9052,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/extraction/extraction.ts","kind":"import-statement","original":"../extraction"},{"path":"src/extraction/quotes.ts","kind":"import-statement","original":"../quotes"},{"path":"src/extraction/extraction-ner-function/named-entity-recognition.ts","kind":"dynamic-import","original":"./named-entity-recognition"}],"format":"esm"},"src/extraction/extraction-ner-function/index.ts":{"bytes":652,"imports":[{"path":"src/extraction/extraction-ner-function/extraction-ner-function.ts","kind":"import-statement","original":"./extraction-ner-function"},{"path":"src/extraction/extraction-ner-function/named-entity-recognition.ts","kind":"import-statement","original":"./named-entity-recognition"}],"format":"esm"},"src/extraction/index.ts":{"bytes":803,"imports":[{"path":"src/extraction/extraction.ts","kind":"import-statement","original":"./extraction"},{"path":"src/extraction/extraction-llm-function/index.ts","kind":"import-statement","original":"./extraction-llm-function"},{"path":"src/extraction/extraction-ner-function/index.ts","kind":"import-statement","original":"./extraction-ner-function"},{"path":"src/extraction/quotes.ts","kind":"import-statement","original":"./quotes"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":37049},"dist/lib/browser/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-3K5SRE5A.mjs","kind":"import-statement"},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AiAssistantError","AiContextBinder","AiContextService","AiConversation","AiModelError","AiSession","ArtifactDiffResolver","ArtifactId","Bindings","ContextBinding","GenerationObserver","VersionPin","applyDiffs","computeDiffsWithCursors","createArtifactElement","createSystemPrompt","createToolkit","makeToolExecutionServiceFromFunctions","makeToolResolverFromFunctions","reduceDiffs","templates"],"entryPoint":"src/index.ts","inputs":{"src/conversation/context.ts":{"bytesInOutput":3877},"src/conversation/index.ts":{"bytesInOutput":0},"src/conversation/conversation.ts":{"bytesInOutput":2807},"src/index.ts":{"bytesInOutput":0},"src/diff.ts":{"bytesInOutput":1899},"src/functions/services.ts":{"bytesInOutput":3431},"src/functions/index.ts":{"bytesInOutput":0},"src/templates/system.ts":{"bytesInOutput":540},"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw":{"bytesInOutput":2000},"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw":{"bytesInOutput":3424},"src/templates/index.ts":{"bytesInOutput":0},"src/types.ts":{"bytesInOutput":1334}},"bytes":20294},"dist/lib/browser/extraction/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":17010},"dist/lib/browser/extraction/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-3K5SRE5A.mjs","kind":"import-statement"},{"path":"dist/lib/browser/chunk-UB26N5UF.mjs","kind":"import-statement"},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"dist/lib/browser/named-entity-recognition-QPYHML66.mjs","kind":"dynamic-import"}],"exports":["ExtractionInput","ExtractionOutput","ReferencedQuotes","combineNerTokens","createTokenGroups","extractFullEntities","extractionAnthropicFunction","extractionNerFunction","findQuotes","getNer","insertReferences","processTranscriptMessage"],"entryPoint":"src/extraction/index.ts","inputs":{"src/extraction/extraction.ts":{"bytesInOutput":1370},"src/extraction/index.ts":{"bytesInOutput":0},"src/extraction/extraction-llm-function/extraction-llm-function.ts":{"bytesInOutput":1766},"src/extraction/quotes.ts":{"bytesInOutput":1673},"raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw":{"bytesInOutput":1376},"src/extraction/extraction-llm-function/index.ts":{"bytesInOutput":0},"src/extraction/extraction-ner-function/extraction-ner-function.ts":{"bytesInOutput":2656},"src/extraction/extraction-ner-function/index.ts":{"bytesInOutput":0}},"bytes":9691},"dist/lib/browser/chunk-3K5SRE5A.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":31160},"dist/lib/browser/chunk-3K5SRE5A.mjs":{"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/errors","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"@effect/platform","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"exports":["AiAssistantError","AiModelError","AiSession","ArtifactDiffResolver","GenerationObserver","VersionPin","createToolkit"],"inputs":{"src/session/artifact-diff.ts":{"bytesInOutput":134},"src/session/observer.ts":{"bytesInOutput":874},"src/errors.ts":{"bytesInOutput":236},"src/session/session.ts":{"bytesInOutput":4674},"src/session/error-handling.ts":{"bytesInOutput":1009},"src/session/format.ts":{"bytesInOutput":3790},"src/session/toolkit.ts":{"bytesInOutput":745},"src/session/version-pin.ts":{"bytesInOutput":1043},"src/session/index.ts":{"bytesInOutput":0}},"bytes":12937},"dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"dist/lib/browser/named-entity-recognition-QPYHML66.mjs":{"imports":[{"path":"dist/lib/browser/chunk-UB26N5UF.mjs","kind":"import-statement"}],"exports":["combineNerTokens","createTokenGroups","extractFullEntities","getNer"],"entryPoint":"src/extraction/extraction-ner-function/named-entity-recognition.ts","inputs":{},"bytes":261},"dist/lib/browser/chunk-UB26N5UF.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5245},"dist/lib/browser/chunk-UB26N5UF.mjs":{"imports":[{"path":"@xenova/transformers","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["combineNerTokens","createTokenGroups","extractFullEntities","getNer"],"inputs":{"src/extraction/extraction-ner-function/named-entity-recognition.ts":{"bytesInOutput":2265}},"bytes":2465}}}
1
+ {"inputs":{"src/conversation/context.ts":{"bytes":16750,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/session/artifact-diff.ts":{"bytes":2575,"imports":[{"path":"effect","kind":"import-statement","external":true}],"format":"esm"},"src/session/observer.ts":{"bytes":5294,"imports":[{"path":"effect","kind":"import-statement","external":true}],"format":"esm"},"src/errors.ts":{"bytes":1420,"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true}],"format":"esm"},"src/session/error-handling.ts":{"bytes":4851,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"@effect/platform","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"../errors"}],"format":"esm"},"src/session/format.ts":{"bytes":16676,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"../errors"},{"path":"src/session/artifact-diff.ts","kind":"import-statement","original":"./artifact-diff"}],"format":"esm"},"src/session/session.ts":{"bytes":22852,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/session/error-handling.ts","kind":"import-statement","original":"./error-handling"},{"path":"src/session/format.ts","kind":"import-statement","original":"./format"},{"path":"src/session/observer.ts","kind":"import-statement","original":"./observer"}],"format":"esm"},"src/session/toolkit.ts":{"bytes":4171,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/session/version-pin.ts":{"bytes":4556,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"format":"esm"},"src/session/index.ts":{"bytes":832,"imports":[{"path":"src/session/artifact-diff.ts","kind":"import-statement","original":"./artifact-diff"},{"path":"src/session/observer.ts","kind":"import-statement","original":"./observer"},{"path":"src/session/session.ts","kind":"import-statement","original":"./session"},{"path":"src/session/toolkit.ts","kind":"import-statement","original":"./toolkit"},{"path":"src/session/version-pin.ts","kind":"import-statement","original":"./version-pin"}],"format":"esm"},"src/conversation/conversation.ts":{"bytes":12652,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/session/index.ts","kind":"import-statement","original":"../session"},{"path":"src/conversation/context.ts","kind":"import-statement","original":"./context"}],"format":"esm"},"src/conversation/index.ts":{"bytes":562,"imports":[{"path":"src/conversation/context.ts","kind":"import-statement","original":"./context"},{"path":"src/conversation/conversation.ts","kind":"import-statement","original":"./conversation"}],"format":"esm"},"src/diff.ts":{"bytes":8472,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/functions/services.ts":{"bytes":14583,"imports":[{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"src/functions/index.ts":{"bytes":460,"imports":[{"path":"src/functions/services.ts","kind":"import-statement","original":"./services"}],"format":"esm"},"raw-loader:./format.tpl?raw":{"bytes":1915,"imports":[]},"raw-loader:./system.tpl?raw":{"bytes":3337,"imports":[]},"src/templates/system.ts":{"bytes":3127,"imports":[{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"raw-loader:./format.tpl?raw","kind":"import-statement","original":"./format.tpl?raw"},{"path":"raw-loader:./system.tpl?raw","kind":"import-statement","original":"./system.tpl?raw"}],"format":"esm"},"src/templates/index.ts":{"bytes":458,"imports":[{"path":"src/templates/system.ts","kind":"import-statement","original":"./system"}],"format":"esm"},"src/types.ts":{"bytes":6867,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":974,"imports":[{"path":"src/conversation/index.ts","kind":"import-statement","original":"./conversation"},{"path":"src/diff.ts","kind":"import-statement","original":"./diff"},{"path":"src/functions/index.ts","kind":"import-statement","original":"./functions"},{"path":"src/session/index.ts","kind":"import-statement","original":"./session"},{"path":"src/templates/index.ts","kind":"import-statement","original":"./templates"},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"src/extraction/extraction.ts":{"bytes":6822,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true}],"format":"esm"},"src/extraction/quotes.ts":{"bytes":7110,"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"raw-loader:./instructions.tpl?raw":{"bytes":1318,"imports":[]},"src/extraction/extraction-llm-function/extraction-llm-function.ts":{"bytes":8479,"imports":[{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/session/index.ts","kind":"import-statement","original":"../../session"},{"path":"src/extraction/extraction.ts","kind":"import-statement","original":"../extraction"},{"path":"src/extraction/quotes.ts","kind":"import-statement","original":"../quotes"},{"path":"raw-loader:./instructions.tpl?raw","kind":"import-statement","original":"./instructions.tpl?raw"}],"format":"esm"},"src/extraction/extraction-llm-function/index.ts":{"bytes":524,"imports":[{"path":"src/extraction/extraction-llm-function/extraction-llm-function.ts","kind":"import-statement","original":"./extraction-llm-function"}],"format":"esm"},"src/extraction/extraction-ner-function/named-entity-recognition.ts":{"bytes":10067,"imports":[{"path":"@xenova/transformers","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/extraction/extraction-ner-function/extraction-ner-function.ts":{"bytes":9052,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"src/extraction/extraction.ts","kind":"import-statement","original":"../extraction"},{"path":"src/extraction/quotes.ts","kind":"import-statement","original":"../quotes"},{"path":"src/extraction/extraction-ner-function/named-entity-recognition.ts","kind":"dynamic-import","original":"./named-entity-recognition"}],"format":"esm"},"src/extraction/extraction-ner-function/index.ts":{"bytes":652,"imports":[{"path":"src/extraction/extraction-ner-function/extraction-ner-function.ts","kind":"import-statement","original":"./extraction-ner-function"},{"path":"src/extraction/extraction-ner-function/named-entity-recognition.ts","kind":"import-statement","original":"./named-entity-recognition"}],"format":"esm"},"src/extraction/index.ts":{"bytes":803,"imports":[{"path":"src/extraction/extraction.ts","kind":"import-statement","original":"./extraction"},{"path":"src/extraction/extraction-llm-function/index.ts","kind":"import-statement","original":"./extraction-llm-function"},{"path":"src/extraction/extraction-ner-function/index.ts","kind":"import-statement","original":"./extraction-ner-function"},{"path":"src/extraction/quotes.ts","kind":"import-statement","original":"./quotes"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":36935},"dist/lib/browser/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-3K5SRE5A.mjs","kind":"import-statement"},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AiAssistantError","AiContextBinder","AiContextService","AiConversation","AiModelError","AiSession","ArtifactDiffResolver","ArtifactId","Bindings","ContextBinding","GenerationObserver","VersionPin","applyDiffs","computeDiffsWithCursors","createArtifactElement","createSystemPrompt","createToolkit","makeToolExecutionServiceFromFunctions","makeToolResolverFromFunctions","reduceDiffs","templates"],"entryPoint":"src/index.ts","inputs":{"src/conversation/context.ts":{"bytesInOutput":3877},"src/conversation/index.ts":{"bytesInOutput":0},"src/conversation/conversation.ts":{"bytesInOutput":2807},"src/index.ts":{"bytesInOutput":0},"src/diff.ts":{"bytesInOutput":1899},"src/functions/services.ts":{"bytesInOutput":3431},"src/functions/index.ts":{"bytesInOutput":0},"src/templates/system.ts":{"bytesInOutput":540},"raw-loader:./format.tpl?raw":{"bytesInOutput":2000},"raw-loader:./system.tpl?raw":{"bytesInOutput":3412},"src/templates/index.ts":{"bytesInOutput":0},"src/types.ts":{"bytesInOutput":1334}},"bytes":20180},"dist/lib/browser/extraction/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":16934},"dist/lib/browser/extraction/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-3K5SRE5A.mjs","kind":"import-statement"},{"path":"dist/lib/browser/chunk-UB26N5UF.mjs","kind":"import-statement"},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"dist/lib/browser/named-entity-recognition-QPYHML66.mjs","kind":"dynamic-import"}],"exports":["ExtractionInput","ExtractionOutput","ReferencedQuotes","combineNerTokens","createTokenGroups","extractFullEntities","extractionAnthropicFunction","extractionNerFunction","findQuotes","getNer","insertReferences","processTranscriptMessage"],"entryPoint":"src/extraction/index.ts","inputs":{"src/extraction/extraction.ts":{"bytesInOutput":1370},"src/extraction/index.ts":{"bytesInOutput":0},"src/extraction/extraction-llm-function/extraction-llm-function.ts":{"bytesInOutput":1766},"src/extraction/quotes.ts":{"bytesInOutput":1673},"raw-loader:./instructions.tpl?raw":{"bytesInOutput":1376},"src/extraction/extraction-llm-function/index.ts":{"bytesInOutput":0},"src/extraction/extraction-ner-function/extraction-ner-function.ts":{"bytesInOutput":2656},"src/extraction/extraction-ner-function/index.ts":{"bytesInOutput":0}},"bytes":9615},"dist/lib/browser/chunk-3K5SRE5A.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":31160},"dist/lib/browser/chunk-3K5SRE5A.mjs":{"imports":[{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/errors","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"@effect/platform","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/blueprints","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/functions","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/schema","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/ai","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"exports":["AiAssistantError","AiModelError","AiSession","ArtifactDiffResolver","GenerationObserver","VersionPin","createToolkit"],"inputs":{"src/session/artifact-diff.ts":{"bytesInOutput":134},"src/session/observer.ts":{"bytesInOutput":874},"src/errors.ts":{"bytesInOutput":236},"src/session/session.ts":{"bytesInOutput":4674},"src/session/error-handling.ts":{"bytesInOutput":1009},"src/session/format.ts":{"bytesInOutput":3790},"src/session/toolkit.ts":{"bytesInOutput":745},"src/session/version-pin.ts":{"bytesInOutput":1043},"src/session/index.ts":{"bytesInOutput":0}},"bytes":12937},"dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"dist/lib/browser/named-entity-recognition-QPYHML66.mjs":{"imports":[{"path":"dist/lib/browser/chunk-UB26N5UF.mjs","kind":"import-statement"}],"exports":["combineNerTokens","createTokenGroups","extractFullEntities","getNer"],"entryPoint":"src/extraction/extraction-ner-function/named-entity-recognition.ts","inputs":{},"bytes":261},"dist/lib/browser/chunk-UB26N5UF.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5245},"dist/lib/browser/chunk-UB26N5UF.mjs":{"imports":[{"path":"@xenova/transformers","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["combineNerTokens","createTokenGroups","extractFullEntities","getNer"],"inputs":{"src/extraction/extraction-ner-function/named-entity-recognition.ts":{"bytesInOutput":2265}},"bytes":2465}}}
@@ -117,7 +117,7 @@ var insertReferences = (text, quotes) => {
117
117
  return text;
118
118
  };
119
119
 
120
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw
120
+ // raw-loader:./instructions.tpl?raw
121
121
  var instructions_default = 'You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ "quote": "earnings report", "id": "01JT0JP9AX0XKGZX4MV4B69VT6" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.';
122
122
 
123
123
  // src/extraction/extraction-llm-function/extraction-llm-function.ts
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-llm-function/instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
3
+ "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:./instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
4
4
  "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Expando } from '@dxos/echo-schema';\nimport { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nexport const ExtractionInput = Schema.Struct({\n message: DataType.Message,\n objects: Schema.optional(Schema.Array(Expando)),\n options: Schema.optional(\n Schema.Struct({\n timeout: Schema.optional(Schema.Number),\n fallbackToRaw: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nexport interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}\n\nexport const ExtractionOutput = Schema.Struct({\n message: DataType.Message,\n timeElapsed: Schema.Number,\n});\nexport interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}\n\nexport type ProcessTranscriptMessageParams = {\n input: ExtractionInput;\n function: FunctionDefinition<ExtractionInput, ExtractionOutput>;\n executor: FunctionExecutor;\n\n options?: {\n /**\n * Timeout for the entity extraction.\n */\n timeout?: number;\n\n /**\n * Fallback to raw text if the entity extraction fails.\n * Otherwise the function will throw an error.\n * @default false\n */\n fallbackToRaw?: boolean;\n };\n};\n\nexport type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Extract entities from the transcript message and add them to the message.\n */\n// TODO(dmaretskyi): Move context to a vector search index.\nexport const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {\n try {\n if (params.options?.timeout && params.options.timeout > 0) {\n return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);\n } else {\n return await params.executor.invoke(params.function, params.input);\n }\n } catch (error) {\n if (params.options?.fallbackToRaw) {\n log.warn('failed to process message, falling back to raw text', { error });\n return {\n message: params.input.message,\n timeElapsed: 0,\n };\n } else {\n throw error;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { AiService } from '@dxos/ai';\nimport { Obj } from '@dxos/echo';\nimport { create } from '@dxos/echo-schema';\nimport { type FunctionDefinition, defineFunction } from '@dxos/functions';\nimport { type ContentBlock, DataType } from '@dxos/schema';\n\nimport { AiSession } from '../../session';\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { ReferencedQuotes, insertReferences } from '../quotes';\n\nimport PROMPT from './instructions.tpl?raw';\n\nexport const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({\n description: 'Extract entities from the transcript message and add them to the message.',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, objects }, context }) => {\n const startTime = performance.now();\n const ai = context.getService(AiService.AiService);\n const session = new AiSession({ operationModel: 'configured' });\n const result = await session.runStructured(ReferencedQuotes, {\n generationOptions: {\n model: '@anthropic/claude-3-5-haiku-20241022',\n },\n client: ai.client,\n systemPrompt: PROMPT,\n history: [\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [\n {\n _tag: 'text',\n text: `<context>${JSON.stringify(objects)}</context>`,\n } satisfies ContentBlock.Text,\n {\n _tag: 'text',\n text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,\n } satisfies ContentBlock.Text,\n ],\n }),\n ],\n artifacts: [],\n prompt: '',\n tools: [],\n } as any); // TODO(burdon): Rewrite test.\n\n return {\n timeElapsed: performance.now() - startTime,\n message: create(DataType.Message, {\n ...message,\n blocks: message.blocks.map((block) =>\n block._tag !== 'transcript'\n ? block\n : {\n ...block,\n text: insertReferences(block.text, result),\n },\n ),\n }),\n };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Filter, Query } from '@dxos/echo';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { ObjectId } from '@dxos/echo-schema';\nimport { DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nexport const ReferencedQuotes = Schema.Struct({\n references: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n quote: Schema.String, // TODO(burdon): Quote?\n }),\n )\n .pipe(Schema.mutable)\n .annotations({\n // TODO(burdon): Does this description make sense?\n description: `\n The references to the context objects that are mentioned in the transcript. \n Quote should match the original transcript text exactly, while id is the id of the context object.\n `,\n }),\n});\nexport type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;\n\nexport const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {\n const references = await Promise.all(\n quotes.map(async (quote) => {\n const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();\n log.info('found quotes in vector index', { objects, quote });\n return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];\n }),\n );\n return { references: references.flat() };\n};\n\n/**\n * Finds and replaces all quotes with DXNs references.\n */\n// TODO(dmaretskyi): Lookup and verifiy ids from provided context.\nexport const insertReferences = (text: string, quotes: ReferencedQuotes) => {\n for (const quote of quotes.references) {\n if (!ObjectId.isValid(quote.id)) {\n continue;\n }\n\n // Use a case-insensitive regular expression to replace the quote.\n const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);\n }\n\n return text;\n};\n", "You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ \"quote\": \"earnings report\", \"id\": \"01JT0JP9AX0XKGZX4MV4B69VT6\" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { asyncTimeout } from '@dxos/async';\nimport { create } from '@dxos/echo-schema';\nimport { DatabaseService, defineFunction } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { findQuotes, insertReferences } from '../quotes';\n\n/**\n * Named Entity Recognition model\n */\n// TODO(mykola): Make it use vector index to query objects and not pass objects as input.\nexport const extractionNerFunction = defineFunction({\n description: 'Extracts named entities from a text',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, options }, context }) => {\n log.info('input', { message, options });\n const startTime = performance.now();\n const { db } = context.getService(DatabaseService);\n const { extractFullEntities } = await import('./named-entity-recognition');\n\n const entitiesPromise = Promise.all(\n message.blocks.map(async (block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return extractFullEntities(block.text);\n }),\n ).then((entities) => entities.flat());\n const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;\n\n log.info('entities', { entities });\n const quoteReferences = await findQuotes(\n entities.map((entity) => entity.word),\n db,\n );\n\n const blocksWithReferences = message.blocks.map((block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text');\n return { ...block, text: insertReferences(block._tag, quoteReferences) };\n });\n\n const messageWithReferences = create(DataType.Message, {\n ...message,\n blocks: blocksWithReferences,\n });\n\n log.info('output', { messageWithReferences });\n return {\n message: messageWithReferences,\n timeElapsed: performance.now() - startTime,\n };\n },\n});\n"],
5
5
  "mappings": ";;;;;;;;;;;;AAIA,SAASA,cAAc;AAEvB,SAASC,oBAAoB;AAC7B,SAASC,eAAe;AAExB,SAASC,WAAW;AACpB,SAASC,gBAAgB;;AAElB,IAAMC,kBAAkBL,OAAOM,OAAO;EAC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ClC,UAAM,EAAEC,qBAAAA,qBAAmB,IAAK,MAAM,OAAO,0CAAA;AAE7C,UAAMC,kBAAkBC,QAAQC,IAC9Bd,QAAQe,OAAOC,IAAI,OAAOC,UAAAA;AACxBC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAOR,qBAAoBM,MAAMG,IAAI;IACvC,CAAA,CAAA,EACAC,KAAK,CAACC,cAAaA,UAASC,KAAI,CAAA;AAClC,UAAMD,WAAWrB,SAASuB,UAAU,MAAMC,cAAab,iBAAiBX,QAAQuB,OAAO,IAAI,MAAMZ;AAEjGT,IAAAA,KAAIC,KAAK,YAAY;MAAEkB;IAAS,GAAA;;;;;;AAChC,UAAMI,kBAAkB,MAAMC,WAC5BL,SAASN,IAAI,CAACY,WAAWA,OAAOC,IAAI,GACpCrB,EAAAA;AAGF,UAAMsB,uBAAuB9B,QAAQe,OAAOC,IAAI,CAACC,UAAAA;AAC/CC,gBAAUD,MAAME,SAAS,gBAAgBF,MAAME,SAAS,QAAA,QAAA;;;;;;;;;AACxD,aAAO;QAAE,GAAGF;QAAOG,MAAMW,iBAAiBd,MAAME,MAAMO,eAAAA;MAAiB;IACzE,CAAA;AAEA,UAAMM,wBAAwBC,QAAOC,UAASC,SAAS;MACrD,GAAGnC;MACHe,QAAQe;IACV,CAAA;AAEA3B,IAAAA,KAAIC,KAAK,UAAU;MAAE4B;IAAsB,GAAA;;;;;;AAC3C,WAAO;MACLhC,SAASgC;MACTI,aAAa9B,YAAYC,IAAG,IAAKF;IACnC;EACF;AACF,CAAA;",
6
6
  "names": ["Schema", "asyncTimeout", "Expando", "log", "DataType", "ExtractionInput", "Struct", "message", "Message", "objects", "optional", "Array", "options", "timeout", "Number", "fallbackToRaw", "Boolean", "ExtractionOutput", "timeElapsed", "processTranscriptMessage", "params", "executor", "invoke", "function", "input", "error", "warn", "AiService", "Obj", "create", "defineFunction", "DataType", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "ReferencedQuotes", "Struct", "references", "Array", "id", "String", "quote", "pipe", "mutable", "annotations", "description", "findQuotes", "quotes", "db", "Promise", "all", "map", "objects", "query", "select", "text", "type", "run", "info", "length", "toString", "flat", "insertReferences", "isValid", "regex", "RegExp", "replace", "fromLocalObjectId", "extractionAnthropicFunction", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "objects", "context", "startTime", "performance", "now", "ai", "getService", "AiService", "session", "AiSession", "operationModel", "result", "runStructured", "ReferencedQuotes", "generationOptions", "model", "client", "systemPrompt", "PROMPT", "history", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "blocks", "_tag", "text", "JSON", "stringify", "artifacts", "prompt", "tools", "timeElapsed", "create", "map", "block", "insertReferences", "asyncTimeout", "create", "DatabaseService", "defineFunction", "invariant", "log", "DataType", "extractionNerFunction", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "options", "context", "log", "info", "startTime", "performance", "now", "db", "getService", "DatabaseService", "extractFullEntities", "entitiesPromise", "Promise", "all", "blocks", "map", "block", "invariant", "_tag", "text", "then", "entities", "flat", "timeout", "asyncTimeout", "quoteReferences", "findQuotes", "entity", "word", "blocksWithReferences", "insertReferences", "messageWithReferences", "create", "DataType", "Message", "timeElapsed"]
@@ -386,11 +386,11 @@ var createStructFieldsFromSchema = (schema) => {
386
386
  import defaultsDeep from "lodash.defaultsdeep";
387
387
  import { Template } from "@dxos/blueprints";
388
388
 
389
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/format.tpl?raw
389
+ // raw-loader:./format.tpl?raw
390
390
  var format_default = "{{! System Core }}\n\n## Input Formats\n\n### Blueprints\n\nYou may be provided with Blueprint definitions that include specific instructions and tools for a given set of tasks.\nBlue print instructions will be enclosed in a <blueprint> tag.\n\n### Context objects\n\nYou may be provided with references to objects that are relevant to the current prompt.\nObjects will be in the form of a <object> tag with a <dxn> element that is the unique key of the object required by many tools.\nThe <typename> element is the type of the object.\n\n<object>\n <dxn>object-id</dxn>\n <typename>example.com/type/TypeName</typename>\n</object>\n\n## Response Formats\n\nIt is very important to respond in the correct format.\nYou response must be valid Markdown.\nIn some cases you should respond with well-formed XML tags along with the content.\nCode snippets should use 2-space indents.\n\n{{#if cot}}\nBefore responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.\nThe <cot> tag should be the first thing in your response.\n{{/if}}\n\n## Block references\n\nYou can reply with a block reference for objects if you have the DXN. For example:\n\n<object>\n <dxn>dxn:queue:data:B6INSIBY3CBEF4M5VZRYBCMAHQMPYK5AJ:01K24XMVHSZHS97SG1VTVQDM5Z:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n<object>\n <dxn>dxn:echo:@:01K24XPK464FSCKVQJAB2H662M</dxn>\n</object>\n\n### Suggestions\n\nEach suggestion must in the form of a proposed action enclosed in a <suggestion> tag.\nExample: <suggestion>Show on a map</suggestion>\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## Toolkit\n\nIf the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.\n\n## Context\n\nThe current date and time is {{DATETIME}}.\n";
391
391
 
392
- // raw-loader:/__w/dxos/dxos/packages/core/assistant/src/templates/system.tpl?raw
393
- var system_default = "{{! System Prompt }}\n\n- You are a helpful assistant called Kai. \n- Your name is Kai and you are powered by different language models.\n- You were created by DXOS and operate inside of Composer and on the DXOS EDGE network.\n- In your initial greeting state your name and make some suggestions based on the current context objects.\n- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\n- Your task is to process user commands and questions and decide how best to respond.\n- In general be concise and direct.\n- Follow all instructions carefully.\n\n## Planning\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints and Artifacts\n\n- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.\n- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.\n- If it is ambiguous, query for existing artifacts first and then decide.\n- If you decide to create an artifact, call the associated tool to create the artifact.\n- Artifacts are stored in the database. Tools are used to create and query artifacts.\n- If you are unsure about creating an artifact ask the user for clarification.\n- Artifacts are mutable objects that can change over the course of the conversation.\n- Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.\n- You must never generate the id of the artifact; only recall the ids that are already in the history.\n- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.\n- You can add suggested actions at the end of your response.\n- Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.\n- Suggested actions must be in the form of a user instruction that you can follow.\n- Suggested actions could include actions that create artifacts.\n- After creating an artifact use a tool to add it to the chat context.\n\n## Context\n\nToday is {{DATETIME}}.\n";
392
+ // raw-loader:./system.tpl?raw
393
+ var system_default = "{{! System Prompt }}\n\nYou are a helpful assistant called Kai. \nYour name is Kai and you are powered by different language models.\nYou were created by DXOS and operate in Composer and on the DXOS EDGE network.\nIn your initial greeting state your name and make some suggestions based on the current context objects.\n\nYou are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.\nYour task is to process user commands and questions and decide how best to respond.\nIn general be concise and direct.\n\nFollow these instructions carefully.\n\n## Include the following steps\n\n- Analyze the structure and type of the content in the user's message.\n- Determine if you complete the task using the available blueprint definitions?\n- If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.\n- Identify which blueprint definitions are relevant to the user's request.\n- Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.\n- Make a final decision on whether to create an artifact and explain your reasoning.\n- Are the required blueprint definitions already available?\n- If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.\n- The require'd artifact tools will be available for use after require.\n- If creating an artifact, outline how you will structure it within the response.\n- Decide if the artifact needs to be shown to the user.\n- Call the show tool to show the artifact to the user.\n- Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.\n\n## Blueprints\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## Context\n\nToday is {{DATETIME}}.\n";
394
394
 
395
395
  // src/templates/system.ts
396
396
  var createSystemPrompt = (options = {}) => Template.process(format_default, defaultsDeep(options, {