@dxos/assistant 0.10.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/extraction.mjs +169 -0
- package/dist/lib/extraction.mjs.map +1 -0
- package/dist/lib/index.mjs +1958 -0
- package/dist/lib/index.mjs.map +1 -0
- package/dist/types/src/request/AiRequest.d.ts +6 -3
- package/dist/types/src/request/AiRequest.d.ts.map +1 -1
- package/dist/types/src/request/AiRequest.test.d.ts +2 -0
- package/dist/types/src/request/AiRequest.test.d.ts.map +1 -0
- package/dist/types/src/request/format.d.ts +2 -2
- package/dist/types/src/request/format.d.ts.map +1 -1
- package/dist/types/src/request/format.test.d.ts +2 -0
- package/dist/types/src/request/format.test.d.ts.map +1 -0
- package/dist/types/src/session/AiContext.d.ts +1 -1
- package/dist/types/src/session/AiContext.d.ts.map +1 -1
- package/dist/types/src/session/AiSession.d.ts +25 -4
- package/dist/types/src/session/AiSession.d.ts.map +1 -1
- package/dist/types/src/session/harness-control.d.ts +4 -0
- package/dist/types/src/session/harness-control.d.ts.map +1 -1
- package/dist/types/src/tool-runtime/services.d.ts +7 -0
- package/dist/types/src/tool-runtime/services.d.ts.map +1 -1
- package/dist/types/src/tool-runtime/services.test.d.ts +2 -0
- package/dist/types/src/tool-runtime/services.test.d.ts.map +1 -0
- package/dist/types/src/util/execution-graph.d.ts.map +1 -1
- package/dist/types/src/util/tracing.d.ts +10 -0
- package/dist/types/src/util/tracing.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +25 -25
- package/src/extraction/quotes.test.ts +4 -4
- package/src/request/AiRequest.test.ts +110 -0
- package/src/request/AiRequest.ts +11 -4
- package/src/request/format.test.ts +93 -0
- package/src/request/format.ts +48 -11
- package/src/session/AiContext.ts +1 -1
- package/src/session/AiSession.test.ts +124 -0
- package/src/session/AiSession.ts +81 -8
- package/src/tool-runtime/services.test.ts +41 -0
- package/src/tool-runtime/services.ts +16 -1
- package/src/util/execution-graph.ts +1 -1
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
- package/dist/lib/neutral/extraction/index.mjs +0 -197
- package/dist/lib/neutral/extraction/index.mjs.map +0 -7
- package/dist/lib/neutral/index.mjs +0 -2047
- package/dist/lib/neutral/index.mjs.map +0 -7
- package/dist/lib/neutral/meta.json +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/util/artifact.ts","../../src/util/diff.ts","../../src/util/errors.ts","../../src/util/error-handling.ts","../../src/util/execution-graph.ts","../../src/util/tracing.ts","../../src/tool-runtime/services.ts","../../src/request/artifact-diff.ts","../../src/request/format.ts","../../src/request/observer.ts","../../src/request/AiRequest.ts","../../src/session/toolkit.ts","../../src/session/AiContext.ts","../../src/session/SessionLink.ts","../../src/session/SessionLoader.ts","../../src/session/Harness.ts","../../src/session/SkillHooks.ts","../../src/session/AiSession.ts","../../src/session/harness-control.ts","../../src/templates/system.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { Database, type Err, Obj, Ref, type Type } from '@dxos/echo';\nimport { EncodedReference } from '@dxos/echo-protocol';\nimport { EID, EntityId, SpaceId } from '@dxos/keys';\nimport { trim } from '@dxos/util';\n\n/**\n * @deprecated\n */\nexport const createArtifactElement = (id: EntityId) => `<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 * @internal\n */\nconst ArtifactURI: Schema.Schema<string> & {\n toEchoURI: (reference: ArtifactURI, owningSpaceId?: SpaceId) => EID.EID;\n resolve: <S extends Type.AnyEntity>(\n schema: S,\n ref: ArtifactURI,\n ) => Effect.Effect<Type.InstanceType<S>, Err.EntityNotFoundError, Database.Service>;\n} = class extends Schema.String.annotations({\n // TODO(dmaretskyi): This section gets overriden.\n description: trim`\n The URI of the referenced object. Protocols accepted:\n - echo://01KG7R1ZXWFMWQ4DA1Q6TN1DG4. \n - space ID, object ID tuple (spaceID:objectID)\n - Only object ID that is assumed to be in the current space (01KG7R1ZXWFMWQ4DA1Q6TN1DG4)\n - dxn:org.dxos.type.calendar:0.1.0 -- named entity from the registry. Absoutely make sure it actually exists in the registry.\n\n URIs can be prepended with an @ symbol for compatibility with in-text references.\n `,\n examples: [\n 'echo://01KG7R1ZXWFMWQ4DA1Q6TN1DG4',\n '@echo://01KG7R1ZXWFMWQ4DA1Q6TN1DG4',\n 'BM3FSHFOMJCHCG5QW7JTVKGYABD2GAA7G:01KG7R1ZXWFMWQ4DA1Q6TN1DG4',\n '01KG7R1ZXWFMWQ4DA1Q6TN1DG4',\n 'dxn:org.dxos.type.calendar:0.1.0',\n '@dxn:org.dxos.type.calendar:0.1.0',\n ],\n}) {\n static toEchoURI(reference: ArtifactURI, owningSpaceId?: SpaceId): EID.EID {\n // Allow @ prefix for compatibility with in-text references.\n const stripped = reference.startsWith('@') ? reference.slice(1) : reference;\n if (stripped.startsWith('echo:') || stripped.startsWith('dxn:')) {\n return EID.parse(stripped);\n } else if (stripped.includes(':')) {\n const [spaceId, objectId] = stripped.split(':');\n if (!SpaceId.isValid(spaceId) || !EntityId.isValid(objectId)) {\n throw new Error(`Unable to parse object reference: ${reference}`);\n }\n // This is a workaround because the current Filter API doesn't work with fully qualified Echo URIs.\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 URIs.\n return spaceId === owningSpaceId\n ? EID.make({ entityId: objectId })\n : EID.make({ spaceId: spaceId, entityId: objectId });\n } else if (EntityId.isValid(stripped)) {\n return EID.make({ entityId: stripped });\n } else {\n throw new Error(`Unable to parse object reference: ${reference}`);\n }\n }\n\n /**\n * Resolves an artifact ID to an object.\n */\n static resolve<S extends Type.AnyEntity>(\n schema: S,\n ref: ArtifactURI,\n ): Effect.Effect<Type.InstanceType<S>, Err.EntityNotFoundError, Database.Service> {\n const uri = ArtifactURI.toEchoURI(ref);\n return Database.resolve(Ref.fromURI(uri), schema);\n }\n};\n\ntype ArtifactURI = Schema.Schema.Type<typeof ArtifactURI>;\n\n/**\n * Schema that decodes ECHO reference object from an LLM-friendly input.\n */\nexport const RefFromLLM = Schema.transform(ArtifactURI, Ref.Ref(Obj.Unknown), {\n decode: (fromA) => {\n const eid = ArtifactURI.toEchoURI(fromA);\n // Normalize to local form: strip any space authority so the ref resolves within the current\n // space context. The AI commonly sends echo://SPACE/ENTITY format (mirroring what it sees in\n // the database context), but cross-space resolution is not yet supported and the space ID\n // encoded in the URI is always the current space anyway.\n return EncodedReference.fromURI(EID.toLocal(eid));\n },\n encode: (toI) => EncodedReference.toURI(toI),\n strict: false,\n}).annotations({\n description: ArtifactURI.ast.annotations.description as string,\n});\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { next as A, type Doc as AutomergeDoc } from '@automerge/automerge';\n\nimport { toCursorRange } from '@dxos/echo-client';\nimport { Doc } from '@dxos/echo-doc';\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// TODO(burdon): Anthropic only.\n// https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool#example-str-replace-command\n// AI_TOOL_NOT_FOUND: str_replace_based_edit_tool\n// 'str_replace_based_edit_tool',\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 default: {\n throw new Error(`Invalid diff format: each line must start with \"- \" or \"+ \", got: ${JSON.stringify(diff)}`);\n }\n }\n }, []);\n};\n\n/**\n * Resolves text diffs against the accessor's current value into cursor-anchored replacements.\n */\nexport const computeDiffsWithCursors = <T>(accessor: Doc.Accessor<T>, diffs: readonly string[]) => {\n return reduceDiffs(diffs)\n .map((diff) => {\n const text = Doc.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\n/**\n * Applies text diffs to the accessor-backed document and returns the resulting string.\n */\nexport const applyDiffs = <T>(\n accessor: Doc.Accessor<T>,\n diffs: readonly string[],\n { errorOnNotFound = false }: { errorOnNotFound?: boolean } = {},\n): string => {\n for (const diff of reduceDiffs(diffs)) {\n accessor.handle.change((doc: AutomergeDoc<T>) => {\n const text = Doc.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 if (errorOnNotFound) {\n throw new Error(`Diff not found: ${diff.match}`);\n } else {\n log.warn('diff not found', diff);\n }\n }\n });\n }\n\n return Doc.getValue<string>(accessor);\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Generic error from AI model.\n */\nexport class AiModelError extends BaseError.extend('AiModelError', 'AI model error') {}\n\n/**\n * Generic error for AI agent execution.\n */\nexport class AiAssistantError extends BaseError.extend('AiAssistantError', 'AI assistant error') {}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as AiError from '@effect/ai/AiError';\nimport * as HttpClientError from '@effect/platform/HttpClientError';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { AiModelError } from './errors';\n\nconst AnthropicErrorResponse = Schema.Struct({\n type: Schema.Literal('error'),\n error: Schema.Struct({\n type: Schema.String,\n message: Schema.String,\n }),\n});\n\n// TODO(dmaretskyi): Needs rework.\nexport const mapAiError = (err: AiError.AiError): Effect.Effect<AiError.AiError> =>\n Effect.gen(function* () {\n const cause = err.cause;\n if (HttpClientError.isHttpClientError(cause) && cause.reason === 'StatusCode') {\n const body = yield* cause.response.json.pipe(\n Effect.flatMap(Schema.decodeUnknown(AnthropicErrorResponse, { exact: false })),\n );\n\n const parsedCause = new AiModelError({\n message: body.error.message,\n context: { model: 'anthropic', type: body.error.type },\n });\n\n return AiError.UnknownError.make({\n description: body.error.message,\n module: err.module,\n method: err.method,\n cause: parsedCause,\n });\n }\n return err;\n }).pipe(Effect.catchAll(() => Effect.succeed(err)));\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { AgentStatus } from '@dxos/ai';\nimport { MESSAGE_PROPERTY_TOOL_CALL_ID } from '@dxos/compute-runtime';\nimport { type Entity, Obj, type Ref } from '@dxos/echo';\nimport { EID, type EntityId } from '@dxos/keys';\nimport { LogLevel } from '@dxos/log';\nimport { ContentBlock, Message } from '@dxos/types';\nimport { isNonNullable } from '@dxos/util';\n\nconst SKIP_BLOCKS: ContentBlock.Any['_tag'][] = ['text'];\n\n/**\n * Mercurial-style Commit.\n */\n// TODO(wittjosiah): Reconcile with @dxos/react-ui-components.\nexport type Commit = {\n id: string;\n parents: string[];\n branch: string;\n icon?: string;\n level?: LogLevel;\n message: string;\n timestamp?: Date;\n tags?: string[];\n};\n\n// TODO(burdon): Add colors?\nenum IconType {\n // General status.\n SUCCESS = 'ph--check-circle--regular',\n WARNING = 'ph--warning-circle--regular',\n ERROR = 'ph--x-circle--regular',\n FLAG = 'ph--flag--regular',\n ROCKET = 'ph--rocket--regular',\n TIMER = 'ph--timer--regular',\n\n // Interactions.\n USER = 'ph--user--regular',\n USER_INTERACTION = 'ph--user-sound--regular',\n AGENT = 'ph--drone--regular',\n THINKING = 'ph--brain--regular',\n LINK = 'ph--link--regular',\n TOOL = 'ph--wrench--regular',\n}\n\n/**\n * Models the execution graph based on a stream of events.\n */\nexport class ExecutionGraph {\n // TODO(dmaretskyi): Evolve the internal state to support chats, functions, circuit workflows, etc.\n private _commits: Commit[] = [];\n private _branchNames = new Set<string>();\n private _lastBlockId: string | undefined;\n\n // Tool call tracking.\n private _toolCallCommitIds = new Map<string, string>(); // toolCallId -> commitId\n private _lastCommitByBranch = new Map<string, string>(); // branch -> last commitId\n private _pendingToolResults = new Map<string, string>(); // toolCallId -> toolResultCommitId\n\n constructor(private readonly _skipBlocks: ContentBlock.Any['_tag'][] = SKIP_BLOCKS) {}\n\n /**\n * Adds events to the graph.\n */\n addEvents(events: Entity.Unknown[]) {\n const sortedEvents = this.sortObjectsByCreated(events);\n for (const event of sortedEvents) {\n if (Obj.instanceOf(Message.Message, event)) {\n this._processMessage(event);\n } else if (Obj.instanceOf(AgentStatus, event)) {\n this._processAgentStatus(event);\n }\n }\n }\n\n /**\n * Processes a message event and creates commits for its blocks.\n */\n private _processMessage(message: Message.Message) {\n const messageCommits = messageToCommits(\n message,\n this._lastBlockId,\n this._toolCallCommitIds,\n this._lastCommitByBranch,\n this._skipBlocks,\n );\n this._commits.push(...messageCommits);\n\n // Track branches.\n messageCommits.forEach((commit) => this._branchNames.add(commit.branch));\n\n // Track tool calls and update pending tool results.\n this._trackToolCalls(messageCommits);\n\n // Update last block ID for sequential chaining.\n if (messageCommits.length > 0) {\n this._lastBlockId = messageCommits[messageCommits.length - 1].id;\n }\n }\n\n /**\n * Processes an AgentStatus event.\n */\n private _processAgentStatus(event: AgentStatus) {\n const branch = this._getToolCallBranch(event.parentMessage, event.toolCallId);\n this._branchNames.add(branch);\n\n const agentStatusCommit: Commit = {\n id: event.id,\n branch,\n message: event.message,\n icon: IconType.FLAG,\n parents: this._getAgentStatusParents(event),\n timestamp: new Date(event.created),\n };\n\n this._commits.push(agentStatusCommit);\n\n // Update last block ID for sequential chaining.\n this._lastBlockId = event.id;\n\n // Update pending tool results to point to this AgentStatus.\n if (event.toolCallId) {\n this._lastCommitByBranch.set(branch, event.id);\n this._updatePendingToolResults(event.toolCallId, event.id);\n }\n }\n\n /**\n * Stable sort: objects with 'created' field are sorted by it, others remain in place.\n */\n private sortObjectsByCreated(objects: any[]) {\n const sortedObjects = objects.slice();\n // Find indices of objects with 'created'\n const createdObjects: { idx: number; obj: any }[] = [];\n sortedObjects.forEach((obj, idx) => {\n if (obj && typeof obj.created === 'string') {\n createdObjects.push({ idx, obj });\n }\n });\n // Sort only the objects with 'created' by their date, stable\n createdObjects.sort((a, b) => {\n const aDate = new Date(a.obj.created).getTime();\n const bDate = new Date(b.obj.created).getTime();\n return aDate - bDate;\n });\n // Place sorted createdObjects back into their original positions\n let createdIdx = 0;\n return sortedObjects.map((obj, _idx) => {\n if (obj && typeof obj.created === 'string') {\n return createdObjects[createdIdx++].obj;\n }\n return obj;\n });\n }\n\n /**\n * Returns the current state of the graph.\n */\n getGraph(lastRequest = false): { branches: string[]; commits: Commit[] } {\n const idx = lastRequest ? this._commits.findLastIndex((c) => c.tags?.includes('user')) : -1;\n const commits = idx === -1 ? this._commits : this._commits.slice(idx);\n\n return {\n branches: Array.from(this._branchNames),\n commits,\n };\n }\n\n /**\n * Tracks tool calls and handles pending tool result updates.\n */\n private _trackToolCalls(commits: Commit[]) {\n commits.forEach((commit) => {\n if (this._isToolCallCommit(commit)) {\n const toolCallId = this._extractToolCallId(commit.id);\n if (toolCallId) {\n this._toolCallCommitIds.set(toolCallId, commit.id);\n }\n }\n\n if (this._isToolResultCommit(commit)) {\n const toolCallId = this._extractToolCallId(commit.id);\n if (toolCallId) {\n this._pendingToolResults.set(toolCallId, commit.id);\n this._handleLateToolResultUpdate(toolCallId, commit.id);\n }\n }\n\n this._lastCommitByBranch.set(commit.branch, commit.id);\n });\n }\n\n /**\n * Updates pending tool results to point to an AgentStatus event.\n */\n private _updatePendingToolResults(toolCallId: string, agentStatusId: string) {\n const toolResultId = this._pendingToolResults.get(toolCallId);\n if (!toolResultId) {\n return;\n }\n\n const toolResultCommit = this._commits.find((c) => c.id === toolResultId);\n if (!toolResultCommit) {\n return;\n }\n\n const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);\n if (!toolCallCommitId) {\n return;\n }\n\n // Replace tool call commit with AgentStatus commit.\n const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);\n if (toolCallIndex !== -1) {\n toolResultCommit.parents[toolCallIndex] = agentStatusId;\n }\n\n this._pendingToolResults.delete(toolCallId);\n }\n\n /**\n * Handles late updates when AgentStatus is processed before tool result.\n */\n private _handleLateToolResultUpdate(toolCallId: string, toolResultId: string) {\n const toolCallCommitId = this._toolCallCommitIds.get(toolCallId);\n if (!toolCallCommitId) {\n return;\n }\n\n const messageId = toolCallCommitId.split('_toolCall_')[0];\n const toolCallBranch = `${messageId}_${toolCallId}`;\n const agentStatusCommitId = this._lastCommitByBranch.get(toolCallBranch);\n\n if (agentStatusCommitId && agentStatusCommitId !== toolCallCommitId) {\n const toolResultCommit = this._commits.find((c) => c.id === toolResultId);\n if (toolResultCommit) {\n const toolCallIndex = toolResultCommit.parents.indexOf(toolCallCommitId);\n if (toolCallIndex !== -1) {\n toolResultCommit.parents[toolCallIndex] = agentStatusCommitId;\n }\n }\n this._pendingToolResults.delete(toolCallId);\n }\n }\n\n /**\n * Gets the branch name for a tool call.\n */\n private _getToolCallBranch(parentMessage?: EntityId, toolCallId?: string): string {\n if (toolCallId) {\n return toolCallId;\n }\n return parentMessage || 'main';\n }\n\n /**\n * Gets the parents for an AgentStatus commit.\n */\n private _getAgentStatusParents(event: AgentStatus): string[] {\n if (event.parentMessage && event.toolCallId) {\n return [getToolCallId(event.parentMessage, event.toolCallId)];\n }\n return [];\n }\n\n /**\n * Checks if a commit is a tool call commit.\n */\n private _isToolCallCommit(commit: Commit): boolean {\n return commit.message.includes('Calling tool');\n }\n\n /**\n * Checks if a commit is a tool result commit.\n */\n private _isToolResultCommit(commit: Commit): boolean {\n return commit.message.includes('Tool call succeeded') || commit.message.includes('Tool error:');\n }\n\n /**\n * Extracts tool call ID from a commit ID.\n */\n private _extractToolCallId(commitId: string): string | undefined {\n const toolCallMatch = commitId.match(/_toolCall_(.+)$/);\n const toolResultMatch = commitId.match(/_toolResult_(.+)$/);\n return toolCallMatch?.[1] || toolResultMatch?.[1];\n }\n}\n\n/**\n * Creates commits for all blocks in a message.\n */\n// TODO(burdon): Pass in AiToolProvider.\nconst messageToCommits = (\n message: Message.Message,\n lastBlockId?: string,\n toolCallIds?: Map<string, string>,\n lastCommitByBranch?: Map<string, string>,\n skipBlocks?: ContentBlock.Any['_tag'][],\n): Commit[] => {\n let previousBlockId: string | undefined = lastBlockId;\n\n return message.blocks\n .map((block, idx) => {\n const branch = getMessageBranch(message);\n const parents = getBlockParents(block, previousBlockId, message, toolCallIds, lastCommitByBranch);\n if (skipBlocks?.includes(block._tag)) {\n return null;\n }\n\n const commit = createBlockCommit(block, message, branch, parents, idx);\n if (commit) {\n previousBlockId = commit.id;\n }\n\n return commit;\n })\n .filter(isNonNullable);\n};\n\n/**\n * Determines the parent commits for a block based on its type and context.\n */\nconst getBlockParents = (\n block: ContentBlock.Any,\n previousBlockId: string | undefined,\n message: Message.Message,\n toolCallIds?: Map<string, string>,\n lastCommitByBranch?: Map<string, string>,\n): string[] => {\n const parents: string[] = [];\n\n if (block._tag === 'toolResult') {\n // Tool results have two parents: previous block and last block from tool call branch.\n if (previousBlockId) {\n parents.push(previousBlockId);\n }\n\n const toolCallCommitId = toolCallIds?.get(block.toolCallId);\n if (toolCallCommitId) {\n const toolCallBranch = getToolCallBranchFromCommitId(toolCallCommitId, block.toolCallId);\n const lastBlockFromToolCallBranch = lastCommitByBranch?.get(toolCallBranch);\n\n if (lastBlockFromToolCallBranch) {\n parents.push(lastBlockFromToolCallBranch);\n } else {\n // Fallback to tool call commit if no AgentStatus exists yet.\n parents.push(toolCallCommitId);\n }\n }\n } else {\n // For other blocks, use previous block as parent (or tool call parent for first block).\n if (previousBlockId) {\n parents.push(previousBlockId);\n } else {\n const toolCallParent = getParentId(message);\n if (toolCallParent) {\n parents.push(toolCallParent);\n }\n }\n }\n\n return parents;\n};\n\n/**\n * Creates a commit for a specific block.\n */\nconst createBlockCommit = (\n block: ContentBlock.Any,\n message: Message.Message,\n branch: string,\n parents: string[],\n idx: number,\n): Commit | null => {\n const timestamp = new Date(message.created);\n switch (block._tag) {\n case 'text':\n if (!block.text.trim().length) {\n return null;\n }\n return {\n id: getGenericBlockId(message.id, idx),\n branch,\n parents,\n timestamp,\n ...(message.sender.role === 'user'\n ? {\n icon: IconType.USER,\n tags: ['user'],\n message: 'Processing request...',\n }\n : {\n icon: IconType.AGENT,\n message: `Response (${block.text.split(' ').length} words)`,\n }),\n } satisfies Commit;\n\n case 'toolCall':\n return {\n id: getToolCallId(message.id, block.toolCallId),\n branch,\n parents,\n timestamp,\n icon: IconType.TOOL,\n level: LogLevel.INFO,\n message: `Calling tool (${block.name})`,\n } satisfies Commit;\n\n case 'toolResult':\n return {\n id: getToolResultId(message.id, block.toolCallId),\n branch,\n parents,\n timestamp,\n icon: block.error ? IconType.ERROR : IconType.SUCCESS,\n level: block.error ? LogLevel.ERROR : LogLevel.INFO,\n message: block.error ? 'Tool error: ' + block.error : 'Tool call succeeded',\n } satisfies Commit;\n\n case 'stats':\n return {\n id: getGenericBlockId(message.id, idx),\n branch,\n parents,\n timestamp,\n icon: IconType.ROCKET,\n level: LogLevel.INFO,\n message: ContentBlock.createStatsMessage(block),\n } satisfies Commit;\n\n case 'status':\n return {\n id: getGenericBlockId(message.id, idx),\n branch,\n parents,\n timestamp,\n message: block.statusText,\n level: LogLevel.INFO,\n icon: IconType.FLAG,\n } satisfies Commit;\n\n case 'reasoning':\n return {\n id: getGenericBlockId(message.id, idx),\n branch,\n parents,\n timestamp,\n message: block.reasoningText ?? 'Thinking...',\n icon: IconType.THINKING,\n } satisfies Commit;\n\n case 'reference':\n return {\n id: getGenericBlockId(message.id, idx),\n branch,\n parents,\n timestamp,\n icon: IconType.LINK,\n message: stringifyRef(block.reference),\n } satisfies Commit;\n\n default:\n return null;\n }\n};\n\n/**\n * Gets the tool call branch name from a tool call commit ID.\n */\nconst getToolCallBranchFromCommitId = (toolCallCommitId: string, toolCallId: string): string => {\n const messageId = toolCallCommitId.split('_toolCall_')[0];\n return `${messageId}_${toolCallId}`;\n};\n\nconst getToolCallId = (messageId: EntityId, toolCallId: string) => `${messageId}_toolCall_${toolCallId}`;\nconst getToolResultId = (messageId: EntityId, toolCallId: string) => `${messageId}_toolResult_${toolCallId}`;\nconst getGenericBlockId = (messageId: EntityId, idx: number) => `${messageId}_block_${idx}`;\n\nconst getBranchName = (options: { parentMessage?: EntityId; toolCallId?: string }) => {\n if (options.toolCallId) {\n return options.toolCallId;\n } else if (options.parentMessage) {\n return options.parentMessage;\n } else {\n return 'main';\n }\n};\n\nconst getMessageBranch = (message: Message.Message) => {\n return getBranchName({\n parentMessage: message.parentMessage,\n toolCallId: message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID],\n });\n};\n\nconst getParentId = (message: Message.Message) => {\n if (message.parentMessage && message.properties?.[MESSAGE_PROPERTY_TOOL_CALL_ID]) {\n return getToolCallId(message.parentMessage, message.properties[MESSAGE_PROPERTY_TOOL_CALL_ID]);\n } else {\n return undefined;\n }\n};\n\nconst stringifyRef = (ref: Ref.Unknown) => {\n if (ref.target) {\n return stringifyObject(ref.target);\n }\n\n const echoUri = EID.tryParse(ref.uri);\n return (echoUri ? EID.getEntityId(echoUri) : undefined) ?? '';\n};\n\nconst stringifyObject = (obj: Obj.Unknown) => {\n return Obj.getLabel(obj) ?? Obj.getTypename(obj) ?? obj.id;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Trace } from '@dxos/compute';\nimport { Obj } from '@dxos/echo';\nimport { Actor, ContentBlock } from '@dxos/types';\n\n/**\n * Partial content block emitted.\n */\nexport const PartialBlock = Trace.EventType('assistant.partialBlock', {\n schema: Schema.Struct({\n messageId: Obj.ID,\n role: Actor.Role,\n block: ContentBlock.Any,\n }),\n isEphemeral: true,\n});\n\n/**\n * Complete content block emitted.\n */\nexport const CompleteBlock = Trace.EventType('assistant.completeBlock', {\n schema: Schema.Struct({\n messageId: Obj.ID,\n role: Actor.Role,\n block: ContentBlock.Any,\n }),\n isEphemeral: false,\n});\n\nexport const AgentRequestBegin = Trace.EventType('assistant.agentRequestBegin', {\n schema: Schema.Struct({}),\n isEphemeral: false,\n});\n\nexport const AgentRequestEnd = Trace.EventType('assistant.agentRequestEnd', {\n schema: Schema.Struct({\n status: Schema.Literal('success', 'error', 'interrupted'),\n error: Schema.optional(Schema.String),\n }),\n isEphemeral: false,\n});\n\n/**\n * Emitted when an MCP server connection fails for a request turn.\n * Ephemeral so that misconfigured/unreachable servers don't pollute the durable feed,\n * but can still be surfaced to the user via the live ephemeral event stream.\n */\nexport const McpServerError = Trace.EventType('assistant.mcpServerError', {\n schema: Schema.Struct({\n url: Schema.String,\n protocol: Schema.Literal('sse', 'http'),\n message: Schema.String,\n }),\n isEphemeral: true,\n});\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Tool from '@effect/ai/Tool';\nimport type * as Toolkit from '@effect/ai/Toolkit';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Record from 'effect/Record';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { AiToolNotFoundError, ToolExecutionService, ToolResolverService } from '@dxos/ai';\nimport { OpaqueToolkit } from '@dxos/ai';\nimport { Operation } from '@dxos/compute';\nimport { todo } from '@dxos/debug';\nimport { DXN, Filter, Ref, Registry } from '@dxos/echo';\nimport { invariant } from '@dxos/invariant';\n\nimport { RefFromLLM } from '../util';\n\nexport const makeToolResolverFromOperations = <R = never>({\n toolkit: extraToolkit = OpaqueToolkit.empty,\n}: { toolkit?: OpaqueToolkit.OpaqueToolkit<never, never, R> } = {}): Layer.Layer<\n ToolResolverService,\n never,\n OpaqueToolkit.OpaqueToolkitProvider | Registry.Service | R\n> => {\n return Layer.effect(\n ToolResolverService,\n Effect.gen(function* () {\n const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;\n const registry = yield* Registry.Service;\n return {\n resolve: (id): Effect.Effect<Tool.Any, AiToolNotFoundError> =>\n Effect.gen(function* () {\n const toolkit = OpaqueToolkit.merge(extraToolkit, toolkitProvider.getToolkit());\n\n const tool = toolkit.toolkit.tools[id];\n if (tool) {\n return tool;\n }\n\n // Normalize to a full DXN key (tool IDs are plain NSIDs, stored keys are full DXNs).\n const key = DXN.isDXN(id) ? id : `dxn:${id}`;\n const results = yield* Effect.promise(() =>\n registry.query(Filter.and(Filter.type(Operation.PersistentOperation), Filter.key(key))).run(),\n );\n if (results.length > 0) {\n return projectFunctionToTool(Operation.deserialize(results[0]));\n }\n return yield* Effect.fail(new AiToolNotFoundError(id));\n }),\n } satisfies Context.Tag.Service<ToolResolverService>;\n }),\n );\n};\n\nexport const makeToolExecutionService = <E, R>(opts: {\n invoke: (tool: Tool.Any, input: unknown) => Effect.Effect<unknown>;\n}): Layer.Layer<ToolExecutionService, never, OpaqueToolkit.OpaqueToolkitProvider> =>\n Layer.effect(\n ToolExecutionService,\n Effect.gen(function* () {\n const toolkitProvider = yield* OpaqueToolkit.OpaqueToolkitProvider;\n const toolkit = toolkitProvider.getToolkit();\n\n const toolkitHandler = yield* toolkit.toolkit.pipe(Effect.provide(toolkit.layer));\n invariant(isHandlerLike(toolkitHandler));\n\n return {\n handlersFor: (toolkit) => {\n const makeHandler = (tool: Tool.Any): ((params: unknown) => Effect.Effect<unknown, any, any>) => {\n return Effect.fn(`toolFunctionHandler ${tool.name}`)(function* (input: any) {\n if (toolkitHandler.tools[tool.name]) {\n if (Tool.isProviderDefined(tool)) {\n throw new Error('Attempted to call a provider-defined tool');\n }\n\n // TODO(wittjosiah): Everything is `never` here.\n const { result } = yield* (toolkitHandler.handle as any)(tool.name, input);\n return result;\n }\n\n return yield* opts.invoke(tool, input).pipe(Effect.catchAllDefect((defect) => Effect.fail(defect)));\n });\n };\n\n return toolkit.of(\n Record.map(toolkit.tools, (tool, _name) => (Tool.isUserDefined(tool) ? makeHandler(tool) : null)) as any,\n ) as any;\n },\n };\n }),\n );\n\nexport const makeToolExecutionServiceFromOperationInvoker = (): Layer.Layer<\n ToolExecutionService,\n never,\n Operation.Service | OpaqueToolkit.OpaqueToolkitProvider\n> => {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n const operationInvoker = yield* Operation.Service;\n\n return makeToolExecutionService({\n invoke: (tool, input) =>\n Effect.gen(function* () {\n const operationDef = getOperationFromTool(tool).pipe(Option.getOrThrow);\n\n return yield* operationInvoker.invoke(operationDef, input).pipe(Effect.orDie);\n }),\n });\n }),\n );\n};\n\nexport const ToolExecutionServices = Layer.mergeAll(\n makeToolResolverFromOperations(),\n makeToolExecutionServiceFromOperationInvoker(),\n);\n\nclass FunctionToolAnnotation extends Context.Tag('@dxos/assistant/FunctionToolAnnotation')<\n FunctionToolAnnotation,\n { definition: Operation.Definition.Any }\n>() {}\n\nexport const getOperationFromTool = (tool: Tool.Any): Option.Option<Operation.Definition.Any> => {\n return Context.getOption(FunctionToolAnnotation)(tool.annotations).pipe(Option.map(({ definition }) => definition));\n};\n\nconst toolCache = new WeakMap<Operation.Definition.Any, Tool.Any>();\n\n/**\n * Empty parameters schema annotated with an explicit JSON schema so that\n * @effect/ai versions that call JSONSchema.fromAST directly (≥0.35.0) still\n * produce a valid `{type: \"object\"}` for the Anthropic API instead of the\n * constEmptyStruct `{anyOf: [{type:\"object\"},{type:\"array\"}]}`.\n */\nconst EMPTY_PARAMETERS_SCHEMA = Schema.Struct({}).annotations({\n [SchemaAST.JSONSchemaAnnotationId]: { type: 'object', properties: {}, required: [], additionalProperties: false },\n});\n\n/**\n * Projects an `Operation.Definition` into an `AiTool`.\n */\nconst projectFunctionToTool = (fn: Operation.Definition.Any): Tool.Any => {\n if (toolCache.has(fn)) {\n return toolCache.get(fn)!;\n }\n\n const fields = createStructFieldsFromSchema(fn.input);\n const parametersSchema = Object.keys(fields).length === 0 ? EMPTY_PARAMETERS_SCHEMA : Schema.Struct(fields);\n const tool = Tool.make(makeToolName(fn.meta.name ?? fn.meta.key), {\n description: fn.meta.description,\n failure: Schema.Any,\n })\n .setParameters(parametersSchema)\n .annotate(FunctionToolAnnotation, { definition: fn });\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.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');\n invariant(toolName.match(/^[a-z_][a-z0-9-_]*$/));\n return toolName;\n};\n\n// TODO(dmaretskyi): Factor out.\n/**\n * Projects an operation input struct into the LLM-facing tool parameter fields, mapping each\n * property through {@link mapSchemaTypeForLLM} (so refs become the model-friendly `RefFromLLM`).\n * Exported for testing.\n */\nexport const createStructFieldsFromSchema = (\n schema: Schema.Schema<any, any>,\n): Record<string, Schema.Schema<any, any>> => {\n switch (schema.ast._tag) {\n case 'TypeLiteral':\n return Object.fromEntries(\n schema.ast.propertySignatures.map((prop) => [prop.name, Schema.make(mapSchemaTypeForLLM(prop.type))]),\n );\n case 'VoidKeyword':\n return {};\n default:\n return todo(`Unsupported schema AST: ${schema.ast._tag}`);\n }\n};\n\n/**\n * Picks an LLM-friendly schema type for the given schema AST.\n * The picked schema type decodes to the original schema type.\n */\nconst mapSchemaTypeForLLM = (ast: SchemaAST.AST): SchemaAST.AST => {\n if (Ref.isRefType(ast)) {\n const description = ast.annotations.description\n ? ast.annotations.description + '\\n' + RefFromLLM.ast.annotations.description\n : (RefFromLLM.ast.annotations.description as string);\n return RefFromLLM.annotations({ description }).ast;\n } else if (SchemaAST.isTupleType(ast)) {\n return new SchemaAST.TupleType(\n ast.elements.map((t) => new SchemaAST.OptionalType(mapSchemaTypeForLLM(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new SchemaAST.Type(mapSchemaTypeForLLM(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n } else if (SchemaAST.isTypeLiteral(ast)) {\n return new SchemaAST.TypeLiteral(\n ast.propertySignatures.map(\n (p) =>\n new SchemaAST.PropertySignature(\n p.name,\n mapSchemaTypeForLLM(p.type),\n p.isOptional,\n p.isReadonly,\n p.annotations,\n ),\n ),\n ast.indexSignatures,\n ast.annotations,\n );\n } else if (SchemaAST.isUnion(ast)) {\n // `Schema.optional(Schema.Array(Ref(...)))` surfaces the value as a `T | undefined` union, so a\n // ref nested inside an optional/union field must be mapped through each member — otherwise it\n // keeps the raw `Ref` encoding and an LLM-supplied URI string is never coerced via `RefFromLLM`.\n return SchemaAST.Union.make(\n ast.types.map((member) => mapSchemaTypeForLLM(member)),\n ast.annotations,\n );\n }\n\n return ast;\n};\n\nconst isHandlerLike = (value: unknown): value is Toolkit.WithHandler<Record<string, Tool.Any>> => {\n return typeof (value as any).tools === 'object' && typeof (value as any).handle === 'function';\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\n\nimport { type ObjectVersion } from '@dxos/echo-client';\nimport { type EntityId } from '@dxos/keys';\n\n/**\n * Resolves artifact ids to their versions.\n * Used to give the model a sense of the changes to the artifacts made by users during the conversation.\n * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,\n * a diff is inserted into the conversation.\n *\n * Can be optionally provided to the session run call.\n */\n// TODO(dmaretskyi): Convert to Context.Reference\nexport class ArtifactDiffResolver extends Context.Tag('@dxos/assistant/ArtifactDiffResolver')<\n ArtifactDiffResolver,\n ArtifactDiffResolver.Service\n>() {}\n\nexport namespace ArtifactDiffResolver {\n export type Service = {\n resolve: (\n artifacts: {\n id: EntityId;\n lastVersion: ObjectVersion;\n }[],\n ) => Promise<\n Map<\n EntityId,\n {\n version: ObjectVersion;\n diff?: string;\n }\n >\n >;\n };\n}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\n\nimport { type FunctionNotFoundError, type Operation, Template } from '@dxos/compute';\nimport { Database, Obj, type Registry } from '@dxos/echo';\nimport { ObjectVersion } from '@dxos/echo-client';\nimport { type EntityNotFoundError } from '@dxos/echo/Err';\nimport { type EntityId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type ContentBlock, Message } from '@dxos/types';\nimport { trim } from '@dxos/util';\n\nimport { AiAssistantError } from '../util';\nimport type * as AiRequest from './AiRequest';\nimport { ArtifactDiffResolver } from './artifact-diff';\n\n/**\n * Formats the system prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\nexport const formatSystemPrompt = ({\n system,\n skills = [],\n objects = [],\n instructions = [],\n}: Pick<AiRequest.RunProps, 'system' | 'skills' | 'objects' | 'instructions'>): Effect.Effect<\n string,\n FunctionNotFoundError | EntityNotFoundError,\n Database.Service | Registry.Service | Operation.Service\n> =>\n Effect.gen(function* () {\n const skillDefs = yield* Function.pipe(\n skills,\n Effect.forEach((skill) => Effect.succeed(skill.instructions)),\n Effect.flatMap(\n Effect.forEach((template) =>\n Effect.gen(function* () {\n return trim`\n <skill>\n ${yield* Template.processTemplate(template)}\n </skill>\n `;\n }),\n ),\n ),\n Effect.map((skills) => (skills.length > 0 ? ['## Skills Definitions', ...skills].join('\\n\\n') : undefined)),\n );\n\n // Instructions steer the session, so their text (and sentinel commands) belongs in the system\n // prompt itself — a context-object stub would force the model to tool-load them and follow nothing.\n const instructionDefs = yield* Function.pipe(\n instructions,\n Effect.forEach((instructions) =>\n Effect.gen(function* () {\n // A broken text ref degrades to commands-only rather than failing the whole prompt.\n const text = yield* Database.load(instructions.text).pipe(\n Effect.map((doc) => doc.content.trim()),\n Effect.catchTag('EntityNotFoundError', () => Effect.succeed('')),\n );\n const commands = (instructions.commands ?? []).map(\n ({ sentinel, description, prompt }) =>\n `- \\`${sentinel}\\`${description ? ` (${description})` : ''}: ${prompt}`,\n );\n const parts = [text];\n if (commands.length > 0) {\n parts.push(\n ['When the user message contains one of these sentinel commands, follow its prompt:', ...commands].join(\n '\\n',\n ),\n );\n }\n return `<instructions>\\n${parts.filter(Boolean).join('\\n\\n')}\\n</instructions>`;\n }),\n ),\n Effect.map((defs) => (defs.length > 0 ? ['## Instructions', ...defs].join('\\n\\n') : undefined)),\n );\n\n const objectDefs = yield* Function.pipe(\n objects,\n Effect.forEach((object) => {\n // Carry the label so the model only tool-loads an object when it needs the contents,\n // not just to learn what the reference is.\n const label = Obj.getLabel(object);\n return Effect.succeed(\n trim`\n <object>\n <dxn>${Obj.getURI(object)}</dxn>\n <typename>${Obj.getTypename(object)}</typename>${label ? `\\n <label>${label}</label>` : ''}\n </object>\n `,\n );\n }),\n Effect.map((objects) => (objects.length > 0 ? ['## Context Objects', ...objects].join('\\n\\n') : undefined)),\n );\n\n return yield* Function.pipe(\n Effect.succeed(\n [system, instructionDefs, skillDefs, objectDefs].filter((def): def is string => def !== undefined),\n ),\n Effect.map((parts) => parts.join('\\n\\n')),\n );\n }).pipe(Effect.withSpan('formatSystemPrompt'));\n\n/**\n * Formats the user prompt.\n */\n// TODO(burdon): Move to AiPreprocessor.\n// TODO(burdon): Convert util below to `Effect.fn` (to preserve stack info)\nexport const formatUserPrompt = ({\n prompt,\n history = [],\n}: Pick<AiRequest.RunProps, 'prompt' | 'history'>): Effect.Effect<Message.Message, AiRequest.RunError> =>\n Effect.gen(function* () {\n const blocks: ContentBlock.Any[] = [];\n\n // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.\n const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);\n if (Option.isSome(artifactDiffResolver)) {\n const versions = gatherObjectVersions(history);\n const artifactDiff = yield* Effect.tryPromise({\n try: () =>\n artifactDiffResolver.value.resolve(\n [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),\n ),\n catch: AiAssistantError.wrap({ message: 'Artifact diff resolution error' }),\n });\n\n log('version', { artifactDiff, versions });\n for (const [id, { version }] of [...artifactDiff.entries()]) {\n if (ObjectVersion.equals(version, versions.get(id)!)) {\n artifactDiff.delete(id);\n continue;\n }\n\n blocks.push({ _tag: 'anchor', objectId: id, version });\n }\n\n if (artifactDiff.size > 0) {\n blocks.push(createArtifactUpdateBlock(artifactDiff));\n }\n }\n\n return Obj.make(Message.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: typeof prompt === 'string' ? [...blocks, { _tag: 'text', text: prompt }] : [...blocks, ...prompt],\n });\n }).pipe(Effect.withSpan('formatUserPrompt'));\n\nconst gatherObjectVersions = (messages: Message.Message[]): Map<EntityId, ObjectVersion> => {\n const artifactIds = new Map<EntityId, ObjectVersion>();\n for (const message of messages) {\n for (const block of message.blocks) {\n if (block._tag === 'anchor') {\n artifactIds.set(block.objectId, block.version as ObjectVersion);\n }\n }\n }\n\n return artifactIds;\n};\n\nconst createArtifactUpdateBlock = (\n artifactDiff: Map<EntityId, { version: ObjectVersion; diff?: string }>,\n): ContentBlock.Any => {\n return {\n _tag: 'text',\n // TODO(dmaretskyi): Does this need to be a special content-block?\n disposition: 'synthetic',\n text: trim`\n The following artifacts have been updated since the last message:\n ${[...artifactDiff.entries()]\n .map(([id, { diff }]) => `<changed-artifact id=\"${id}\">${diff ? `\\n${diff}` : ''}</changed-artifact>`)\n .join('\\n')}\n `,\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Tool from '@effect/ai/Tool';\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\n\nimport { type AiParser, type ConsolePrinter } from '@dxos/ai';\nimport { type Message } from '@dxos/types';\n\n/**\n * Live observer of the generation process.\n */\nexport interface GenerationObserver<\n Tools extends Record<string, Tool.Any> = any,\n> extends AiParser.ParseResponseCallbacks<Tools> {\n /**\n * Complete messages fired during the session, both from the model and from the user.\n * This message will contain all message blocks emitted through the `onBlock` callback.\n */\n onMessage: (message: Message.Message) => Effect.Effect<void>;\n}\n\nexport const GenerationObserver = Object.freeze({\n make: ({\n onBegin = Function.constant(Effect.void),\n onPart = Function.constant(Effect.void),\n onBlock = Function.constant(Effect.void),\n onEnd = Function.constant(Effect.void),\n onMessage = Function.constant(Effect.void),\n }: Partial<GenerationObserver> = {}): GenerationObserver => ({\n onBegin,\n onPart,\n onBlock,\n onEnd,\n onMessage,\n }),\n\n noop: () => GenerationObserver.make(),\n\n /**\n * Debug printer to be used in unit-tests and browser devtools.\n */\n fromPrinter: (printer: ConsolePrinter) =>\n GenerationObserver.make({\n onBlock: (block) =>\n Effect.sync(() => {\n if (block.pending) {\n return; // Only prints full blocks (better for unit-tests and browser devtools).\n }\n printer.printContentBlock(block);\n }),\n onMessage: (message) =>\n Effect.sync(() => {\n if (message.sender.role === 'assistant') {\n return; // Skip assistant messages since they are printed in the `onBlock` callback.\n }\n printer.printMessage(message);\n }),\n }),\n});\n","//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as AiError from '@effect/ai/AiError';\nimport * as LanguageModel from '@effect/ai/LanguageModel';\nimport type * as Toolkit from '@effect/ai/Toolkit';\nimport * as Array from 'effect/Array';\nimport * as Chunk from 'effect/Chunk';\nimport * as Effect from 'effect/Effect';\nimport { pipe } from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as Stream from 'effect/Stream';\n\nimport {\n AiParser,\n AiPreprocessor,\n AiSummarizer,\n type AiToolNotFoundError,\n type OpaqueToolkit,\n type PromptPreprocessingError,\n type ToolExecutionService,\n type ToolResolverService,\n callTool,\n withoutToolCallParising,\n} from '@dxos/ai';\nimport { type Instructions, Operation, type Skill, Trace } from '@dxos/compute';\nimport { Database, Obj, Registry } from '@dxos/echo';\nimport { log } from '@dxos/log';\nimport { ContentBlock, Message } from '@dxos/types';\n\nimport { getOperationFromTool } from '../tool-runtime/services';\nimport { type AiAssistantError, CompleteBlock, PartialBlock } from '../util';\nimport { formatSystemPrompt, formatUserPrompt } from './format';\nimport { GenerationObserver } from './observer';\n\nexport type RunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;\n\nexport type RunRequirements =\n | LanguageModel.LanguageModel\n | ToolExecutionService\n | ToolResolverService\n | Database.Service\n | Operation.Service\n | Registry.Service\n | Trace.TraceService;\n\nexport type Options = {\n /**\n * Summarize before executing the prompt if the existing history exceeds this threshold.\n */\n summarizationThreshold?: number;\n\n // TODO(dmaretskyi): Plan to phase out in favor of TracingService and the return type being a stream.\n observer?: GenerationObserver;\n /**\n * Callback for when a message is received from the user, model, or tool.\n * This is useful for streaming the output to a queue.\n */\n onOutput?: (message: Message.Message) => Effect.Effect<void, never, never>;\n\n /**\n * When false, turn messages are not appended to the feed or written as persisted trace blocks.\n *\n * @default true\n */\n persist?: boolean;\n};\n\nexport type RunProps<R = never> = {\n prompt: string | ContentBlock.Any[];\n // TODO(wittjosiah): Rename to systemPrompt.\n system?: string;\n history?: Message.Message[];\n objects?: Obj.Unknown[];\n skills?: readonly Skill.Skill[];\n /** Rendered inline into the system prompt; passed explicitly rather than inferred from `objects`. */\n instructions?: readonly Instructions.Instructions[];\n toolkit?: OpaqueToolkit.OpaqueToolkit<R>;\n};\n\nexport type BeginProps = {\n prompt: string | ContentBlock.Any[];\n system?: string;\n history?: Message.Message[];\n objects?: Obj.Unknown[];\n skills?: readonly Skill.Skill[];\n instructions?: readonly Instructions.Instructions[];\n};\n\nexport type TurnProps<R = never> = {\n system: string;\n toolkit?: OpaqueToolkit.OpaqueToolkit<R>;\n};\n\nexport type TurnResult = {\n messages: Message.Message[];\n done: boolean;\n /**\n * Provider finish reason for this turn. `pause` means the provider paused a server-tool turn\n * mid-execution (e.g. Anthropic `pause_turn`) and the turn must be resumed by issuing another\n * request without mutating the trailing assistant content.\n */\n finishReason?: ContentBlock.FinishReason;\n};\n\n/**\n * Contains message history, tools, current context.\n * Current context means the state of the app, time of day, and other contextual information.\n * It makes requests to the model, its a state machine.\n * It keeps track of the current goal.\n * It manages the context window.\n * Tracks the success criteria of reaching the goal, exposing metrics (stretch).\n * Could be run locally in the app or remotely.\n * Could be personal or shared.\n */\nexport class Request {\n /** Prevents concurrent execution of session. */\n private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));\n\n private readonly _observer: GenerationObserver;\n private readonly _onOutput: (message: Message.Message) => Effect.Effect<void, never, never>;\n\n /** Message history from queue. */\n // TODO(burdon): Evolve into supporting a git-like graph of messages.\n private _history: Message.Message[] = [];\n\n /** Pending messages for this session (incl. the current prompt). */\n private _pending: Message.Message[] = [];\n\n private _started = 0;\n private _ended = 0;\n private _toolCalls = 0;\n\n constructor(private readonly _options: Options = {}) {\n this._observer = _options.observer ?? GenerationObserver.noop();\n this._onOutput = _options.onOutput ?? (() => Effect.void);\n }\n\n get duration(): number {\n return this._ended - this._started;\n }\n\n get toolCalls(): number {\n return this._toolCalls;\n }\n\n get pending(): readonly Message.Message[] {\n return this._pending;\n }\n\n private _submitMessage = (message: Message.Message): Effect.Effect<Message.Message, never, Trace.TraceService> =>\n Effect.gen(this, function* () {\n this._pending.push(message);\n yield* this._observer.onMessage(message);\n if (this._options.persist === false) {\n return message;\n }\n for (const block of message.blocks) {\n log('write complete block', {\n messageId: message.id,\n role: message.sender.role!,\n block: JSON.stringify(block),\n });\n yield* Trace.write(CompleteBlock, {\n messageId: message.id,\n role: message.sender.role!,\n block,\n });\n }\n yield* this._onOutput(message);\n return message;\n });\n\n getToolCalls = () =>\n pipe(\n [...this._history, ...this._pending],\n Array.reverse,\n Array.takeWhile((_) => _.sender.role === 'assistant'),\n Array.flatMap((_) => _.blocks.filter(ContentBlock.is('toolCall')).map((block) => ({ block, message: _ }))),\n Array.filter((_) => !_.block.providerExecuted),\n Array.reverse,\n );\n\n /**\n * Initialize a session: set up history, perform summarization if needed, and submit the user prompt.\n * Must be called before `runTurn()`.\n */\n begin = ({\n prompt,\n system,\n history = [],\n skills = [],\n objects = [],\n instructions = [],\n }: BeginProps): Effect.Effect<void, RunError, RunRequirements> =>\n Effect.gen(this, function* () {\n this._started = Date.now();\n this._history = [...history];\n this._pending = [];\n\n const systemPrompt = yield* formatSystemPrompt({ system, skills, objects, instructions }).pipe(Effect.orDie);\n\n if (this._options.summarizationThreshold !== undefined) {\n const tokenCount = yield* AiPreprocessor.estimateTokens(\n yield* AiPreprocessor.preprocessPrompt([...this._history], {\n system: systemPrompt,\n }),\n );\n if (tokenCount > this._options.summarizationThreshold) {\n const summary = yield* AiSummarizer.summarize([...this._history]);\n yield* this._submitMessage(summary);\n }\n }\n\n yield* this._submitMessage(yield* formatUserPrompt({ prompt, history }));\n }).pipe(Effect.withSpan('AiRequest.begin'));\n\n /**\n * Execute a single turn: one LLM generation followed by tool execution.\n * The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled skills).\n */\n runAgentTurn = <const R = never>({\n system,\n toolkit: opaqueToolkit,\n }: TurnProps<R>): Effect.Effect<TurnResult, RunError, RunRequirements | R> =>\n Effect.gen(this, function* () {\n log('request', {\n system: { snippet: createSnippet(system), length: system.length },\n pending: this._pending.length,\n history: this._history.length,\n });\n\n const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {\n system,\n cacheControl: 'ephemeral',\n });\n\n const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;\n\n const observer = this._observer;\n let currentMessageId: Obj.ID | null = null;\n let finishReason: ContentBlock.FinishReason | undefined;\n\n const messages = yield* LanguageModel.streamText({\n prompt,\n toolkit,\n disableToolCallResolution: true,\n }).pipe(\n withoutToolCallParising,\n AiParser.parseResponse({\n emitPartial: true,\n onBegin: () => observer.onBegin(),\n onBlock: (block) => observer.onBlock(block),\n onPart: (part) => observer.onPart(part as any),\n onEnd: (summary) => observer.onEnd(summary),\n }),\n Stream.map((block) => enrichToolCallBlock(block, toolkit)),\n Stream.mapEffect(\n (block) =>\n Effect.gen(this, function* () {\n if (block._tag === 'stats' && block.finishReason !== undefined) {\n finishReason = block.finishReason;\n }\n if (block.pending) {\n currentMessageId ??= Obj.ID.random();\n log('emit ephemeral message', { id: currentMessageId, type: block._tag });\n yield* Trace.write(PartialBlock, {\n messageId: currentMessageId,\n role: 'assistant',\n block,\n });\n return Option.none();\n } else {\n currentMessageId ??= Obj.ID.random();\n const id = currentMessageId;\n currentMessageId = null;\n log('emit complete message', { id, type: block._tag });\n const message = Obj.make(Message.Message, {\n id,\n created: new Date().toISOString(),\n sender: { role: 'assistant' },\n blocks: [block],\n });\n return Option.some(yield* this._submitMessage(message));\n }\n }),\n { concurrency: 1, unordered: false },\n ),\n Stream.filterMap((_) => _),\n Stream.runCollect,\n Effect.map(Chunk.toArray),\n );\n log('messages', { messages });\n\n // A paused server-tool turn (e.g. Anthropic `pause_turn`) is not complete: the provider\n // expects the assistant content to be resent so it can finish executing the server tool.\n // No local tool execution is needed — just another request.\n if (finishReason === 'pause') {\n return { messages, done: false, finishReason };\n }\n\n const toolCalls = this.getToolCalls();\n\n if (toolCalls.length === 0) {\n this._ended = Date.now();\n return { messages, done: true, finishReason };\n } else if (!toolkit) {\n throw new Error('No toolkit provided');\n }\n\n return { messages, done: false, finishReason };\n }).pipe(Effect.withSpan('AiRequest.runAgentTurn'));\n\n runTools = <const R = never>({\n toolkit: opaqueToolkit,\n }: {\n toolkit?: OpaqueToolkit.OpaqueToolkit<R>;\n }): Effect.Effect<void, RunError, RunRequirements | R> =>\n Effect.gen(this, function* () {\n const toolkit = opaqueToolkit ? yield* opaqueToolkit.handlers : undefined;\n const toolCalls = this.getToolCalls();\n const toolResults = yield* Effect.forEach(toolCalls, ({ block, message }) => {\n if (!toolkit) {\n throw new Error('No toolkit provided');\n }\n return callTool(toolkit, block);\n });\n\n yield* this._submitMessage(\n Obj.make(Message.Message, {\n created: new Date().toISOString(),\n sender: { role: 'tool' },\n blocks: toolResults,\n }),\n );\n\n this._toolCalls += toolResults.length;\n }).pipe(Effect.withSpan('AiRequest.runTools'));\n\n /**\n * Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.\n */\n run = <const R = never>({\n prompt,\n system: systemTemplate,\n history = [],\n objects = [],\n skills = [],\n instructions = [],\n toolkit,\n }: RunProps<R>): Effect.Effect<Message.Message[], RunError, RunRequirements | R> =>\n Effect.gen(this, function* () {\n yield* this.begin({ prompt, system: systemTemplate, history, objects, skills, instructions });\n\n const system = yield* formatSystemPrompt({ system: systemTemplate, skills, objects, instructions }).pipe(\n Effect.orDie,\n );\n\n do {\n const { done, finishReason } = yield* this.runAgentTurn({ system, toolkit });\n if (done) {\n break;\n }\n // A paused server-tool turn resumes with another request and no local tool execution.\n if (finishReason === 'pause') {\n continue;\n }\n yield* this.runTools({ toolkit });\n } while (true);\n\n log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });\n return this._pending;\n }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiRequest.run'));\n}\n\n/**\n * Annotates `toolCall` blocks with metadata about the backing Operation, when one exists.\n * Tool calls that resolve to a toolkit handler (no Operation) are left unchanged so callers can\n * distinguish operation invocations from inline tool calls.\n */\nconst enrichToolCallBlock = (\n block: ContentBlock.Any,\n toolkit: Toolkit.WithHandler<any> | undefined,\n): ContentBlock.Any => {\n if (block._tag !== 'toolCall' || !toolkit) {\n return block;\n }\n const tool = toolkit.tools[block.name];\n if (!tool) {\n return block;\n }\n // Some tools (provider-defined, raw MCP) don't carry an Effect `Context` for annotations and\n // `getOperationFromTool` throws. Be defensive: treat any failure as \"no operation\".\n let operationOpt: Option.Option<Operation.Definition.Any>;\n try {\n operationOpt = getOperationFromTool(tool);\n } catch {\n return block;\n }\n if (Option.isNone(operationOpt)) {\n return block;\n }\n const { meta } = operationOpt.value;\n return {\n ...block,\n operationKey: meta.key,\n operationName: meta.name,\n operationIcon: meta.icon,\n } satisfies ContentBlock.ToolCall;\n};\n\nconst createSnippet = (text: string, len = 32) =>\n text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');\n\n// TODO(dmaretskyi): Extract as a general util.\nconst logDump = (message: string, data: unknown) => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { writeFileSync } = require('node:fs');\n const path = `/tmp/log-data-${Date.now()}.json`;\n writeFileSync(path, JSON.stringify(data, null, 2));\n log.info(message, { path });\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Toolkit from '@effect/ai/Toolkit';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { type AiToolNotFoundError, OpaqueToolkit, ToolExecutionService, ToolResolverService } from '@dxos/ai';\nimport { type Skill } from '@dxos/compute';\nimport { isTruthy } from '@dxos/util';\n\nexport type CreateToolkitProps = {\n toolkit?: OpaqueToolkit.Any;\n skills?: readonly Skill.Skill[];\n /**\n * Self-contained with handlers toolkits.\n */\n opaqueToolkits?: readonly OpaqueToolkit.Any[];\n};\n\n/**\n * Build a combined toolkit from the skill tools and the provided toolkit.\n */\nexport const createToolkit = ({\n toolkit: toolkitProp,\n skills = [],\n opaqueToolkits = [],\n}: CreateToolkitProps): Effect.Effect<\n OpaqueToolkit.OpaqueToolkit,\n AiToolNotFoundError,\n ToolResolverService | ToolExecutionService\n> =>\n Effect.gen(function* () {\n const skillToolkit = yield* ToolResolverService.resolveToolkit(skills.flatMap(({ tools }) => tools));\n const skillToolHandler = yield* skillToolkit.toContext(ToolExecutionService.handlersFor(skillToolkit));\n const opaqueToolkit = OpaqueToolkit.merge(...opaqueToolkits);\n\n const toolkitDefs = [toolkitProp?.toolkit, skillToolkit, opaqueToolkit.toolkit].filter(isTruthy);\n const mergedToolkit = Toolkit.merge(...toolkitDefs);\n const combinedHandlerLayer = Layer.mergeAll(\n Layer.succeedContext(skillToolHandler),\n toolkitProp?.layer ?? OpaqueToolkit.empty.layer,\n opaqueToolkit.layer,\n );\n return OpaqueToolkit.make(mergedToolkit, combinedHandlerLayer as any) as OpaqueToolkit.OpaqueToolkit;\n }) as Effect.Effect<OpaqueToolkit.OpaqueToolkit, AiToolNotFoundError, ToolResolverService | ToolExecutionService>;\n","//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { Atom, Registry as AtomRegistry } from '@effect-atom/atom';\nimport * as EArray from 'effect/Array';\nimport * as Function from 'effect/Function';\nimport * as Runtime from 'effect/Runtime';\nimport * as Schema from 'effect/Schema';\n\nimport { Skill } from '@dxos/compute';\nimport { Resource } from '@dxos/context';\nimport { Annotation, Database, DXN, Feed, Obj, Query, type QueryResult, Ref, Type } from '@dxos/echo';\nimport { assertArgument } from '@dxos/invariant';\nimport { EID, type URI } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexSet, isNonNullable } from '@dxos/util';\n\n/**\n * Thread message that binds or unbinds contextual objects to a conversation.\n */\nexport class Binding extends Type.makeObject<Binding>(DXN.make('org.dxos.type.contextBinding', '0.1.0'))(\n Schema.Struct({\n skills: Schema.Struct({\n added: Schema.Array(Ref.Ref(Skill.Skill)),\n removed: Schema.Array(Ref.Ref(Skill.Skill)),\n }),\n\n objects: Schema.Struct({\n added: Schema.Array(Ref.Ref(Obj.Unknown)),\n removed: Schema.Array(Ref.Ref(Obj.Unknown)),\n }),\n }).pipe(Annotation.HiddenAnnotation.set(true)),\n) {}\nexport type BindingProps = Partial<{\n skills: Ref.Ref<Skill.Skill>[];\n objects: Ref.Ref<Obj.Unknown>[];\n}>;\n\nexport class Bindings {\n readonly skills = new ComplexSet<Ref.Ref<Skill.Skill>>((ref) => ref.uri);\n\n // TODO(burdon): Some DXNs have the Space prefix so only compare the object ID.\n readonly objects = new ComplexSet<Ref.Ref<Obj.Unknown>>((ref) => {\n const echoUri = EID.tryParse(ref.uri);\n return echoUri ? EID.getEntityId(echoUri) : undefined;\n });\n\n toJSON(): { skills: URI.URI[]; objects: URI.URI[] } {\n return {\n skills: EArray.fromIterable(this.skills).map((ref) => ref.uri),\n objects: EArray.fromIterable(this.objects).map((ref) => ref.uri),\n };\n }\n}\n\nexport type BinderOptions = {\n feed: Feed.Feed;\n runtime: Runtime.Runtime<Database.Service>;\n /** @effect-atom/atom-react Registry for reactive state management. */\n registry?: AtomRegistry.Registry;\n};\n\n/**\n * Manages bindings of skills and objects to a conversation.\n */\n// TODO(burdon): Context should manage ephemeral state of bindings until prompt is issued?\nexport class Binder extends Resource {\n private readonly _skills = Atom.make<Skill.Skill[]>([]).pipe(Atom.keepAlive);\n private readonly _objects = Atom.make<Obj.Unknown[]>([]).pipe(Atom.keepAlive);\n private readonly _registry: AtomRegistry.Registry;\n private readonly _feed: Feed.Feed;\n private readonly _runtime: Runtime.Runtime<Database.Service>;\n\n #bindingsQuery: QueryResult.QueryResult<Binding> | undefined;\n\n constructor(options: BinderOptions) {\n super();\n assertArgument(options.feed, 'options.feed', 'Feed is required');\n assertArgument(options.runtime, 'options.runtime', 'Feed runtime is required');\n this._feed = options.feed;\n this._runtime = options.runtime;\n this._registry = options.registry ?? AtomRegistry.make();\n }\n\n /**\n * Returns the skills atom for subscription.\n */\n get skills(): Atom.Atom<Skill.Skill[]> {\n return this._skills;\n }\n\n /**\n * Returns the objects atom for subscription.\n */\n get objects(): Atom.Atom<Obj.Unknown[]> {\n return this._objects;\n }\n\n /**\n * Gets the current skills value.\n */\n getSkills(): Skill.Skill[] {\n return this._registry.get(this._skills);\n }\n\n /**\n * Gets the current objects value.\n */\n getObjects(): Obj.Unknown[] {\n return this._registry.get(this._objects);\n }\n\n /**\n * Subscribe to changes in skills.\n */\n subscribeSkills(cb: (skills: Skill.Skill[]) => void): () => void {\n return this._registry.subscribe(this._skills, () => cb(this._registry.get(this._skills)));\n }\n\n /**\n * Subscribe to changes in objects.\n */\n subscribeObjects(cb: (objects: Obj.Unknown[]) => void): () => void {\n return this._registry.subscribe(this._objects, () => cb(this._registry.get(this._objects)));\n }\n\n protected override async _open(): Promise<void> {\n this.#bindingsQuery = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Query.type(Binding)));\n\n // Process initial state before returning.\n const initialResults = await this.#bindingsQuery.run();\n await this._updateBindings(initialResults);\n\n // Subscribe to future changes.\n this._ctx.onDispose(\n this.#bindingsQuery.subscribe(async () => {\n await this._updateBindings(this.#bindingsQuery!.results);\n }),\n );\n }\n\n /**\n * Re-reads bindings from the feed to pick up changes made by other processes.\n */\n async sync(): Promise<void> {\n if (this.#bindingsQuery) {\n const results = await this.#bindingsQuery.run();\n log('sync', { bindingItems: results.length });\n await this._updateBindings(results);\n log('sync complete', {\n skills: this._registry.get(this._skills).length,\n skillKeys: this._registry.get(this._skills).map((bp) => Skill.getKey(bp)),\n });\n }\n }\n\n private async _updateBindings(items: Binding[]): Promise<void> {\n // Skip update if no items - preserve existing state set by bind().\n if (items.length === 0) {\n return;\n }\n\n const bindings = this._reduce(items);\n\n log('_updateBindings', {\n items: items.length,\n skillRefs: [...bindings.skills].map((ref) => ({ uri: ref.uri, available: ref.isAvailable })),\n });\n\n // Resolve references (loading them first if needed).\n const currentSkills = this._registry.get(this._skills);\n const currentObjects = this._registry.get(this._objects);\n const resolvedSkills = await this._resolve(bindings.skills, currentSkills);\n const resolvedObjects = await this._resolve(bindings.objects, currentObjects);\n\n log('_updateBindings resolved', {\n resolvedSkills: resolvedSkills.length,\n resolvedSkillKeys: resolvedSkills.map((bp) => Obj.getMeta(bp).key ?? '<missing>'),\n });\n\n // Drop skills that have no registry key — they cannot be used downstream\n // (e.g. tool/operation registration calls Skill.getKey which throws).\n const keyedSkills = resolvedSkills.filter((bp) => {\n if (Obj.getMeta(bp).key === undefined) {\n log.warn('dropping skill with no meta key', { uri: Obj.getURI(bp) });\n return false;\n }\n return true;\n });\n\n // Filter current state to only items still in the reduced binding set,\n // then merge in newly resolved items. This ensures unbind events are respected.\n const reducedSkillDxns = new Set<URI.URI>([...bindings.skills].map((ref) => ref.uri));\n const reducedObjectDxns = new Set<URI.URI>([...bindings.objects].map((ref) => ref.uri));\n const filteredSkills = currentSkills.filter((obj) => {\n const uri = Obj.getURI(obj);\n return uri != null && reducedSkillDxns.has(uri) && Obj.getMeta(obj).key !== undefined;\n });\n const filteredObjects = currentObjects.filter((obj) => {\n const uri = Obj.getURI(obj);\n return uri != null && reducedObjectDxns.has(uri);\n });\n const mergedSkills = this._mergeInto(filteredSkills, keyedSkills);\n const mergedObjects = this._mergeInto(filteredObjects, resolvedObjects);\n\n this._registry.set(this._skills, mergedSkills);\n this._registry.set(this._objects, mergedObjects);\n\n log('updated bindings', {\n skills: mergedSkills.length,\n objects: mergedObjects.length,\n });\n }\n\n protected override async _close(): Promise<void> {\n // Reset atoms to empty state.\n this._registry.set(this._skills, []);\n this._registry.set(this._objects, []);\n }\n\n async bind({ skills, objects }: BindingProps): Promise<void> {\n const currentSkills = this._registry.get(this._skills);\n const currentObjects = this._registry.get(this._objects);\n\n const { added: addedSkills, next: nextSkills } = this._processBindings(skills, currentSkills);\n const { added: addedObjects, next: nextObjects } = this._processBindings(objects, currentObjects);\n if (!addedSkills.length && !addedObjects.length) {\n return;\n }\n\n // Atomic updates - subscribers notified automatically.\n this._registry.set(this._skills, nextSkills);\n this._registry.set(this._objects, nextObjects);\n\n log('bind', { skills: addedSkills.length, objects: addedObjects.length });\n await Runtime.runPromise(this._runtime)(\n Feed.append(this._feed, [\n Obj.make(Binding, {\n skills: {\n added: addedSkills,\n removed: [],\n },\n objects: {\n added: addedObjects,\n removed: [],\n },\n }),\n ]),\n );\n }\n\n async unbind({ skills, objects }: BindingProps): Promise<void> {\n if (!skills?.length && !objects?.length) {\n return;\n }\n\n // Immediately update atom state so removals are reflected before the queue round-trips.\n const removedSkillDxns = (skills ?? []).map((ref) => ref.uri);\n const removedObjectDxns = (objects ?? []).map((ref) => ref.uri);\n if (removedSkillDxns.length > 0) {\n const current = this._registry.get(this._skills);\n this._registry.set(\n this._skills,\n current.filter((obj) => !removedSkillDxns.some((uri) => Obj.getURI(obj) === uri)),\n );\n }\n if (removedObjectDxns.length > 0) {\n const current = this._registry.get(this._objects);\n this._registry.set(\n this._objects,\n current.filter((obj) => !removedObjectDxns.some((uri) => Obj.getURI(obj) === uri)),\n );\n }\n\n log('unbind', { skills: skills?.length, objects: objects?.length });\n await Runtime.runPromise(this._runtime)(\n Feed.append(this._feed, [\n Obj.make(Binding, {\n skills: {\n added: [],\n removed: skills ?? [],\n },\n objects: {\n added: [],\n removed: objects ?? [],\n },\n }),\n ]),\n );\n }\n\n /**\n * Process bindings to filter duplicates and determine next state.\n */\n private _processBindings<T extends Obj.Unknown>(\n refs: Ref.Ref<T>[] | undefined,\n current: T[],\n ): { added: Ref.Ref<T>[]; next: T[] } {\n const next = [...current];\n const added: Ref.Ref<T>[] = [];\n if (!refs?.length) {\n return { added, next };\n }\n\n const seen = new Set<URI.URI>(current.map((obj) => Obj.getURI(obj)));\n for (const ref of refs) {\n const uri = ref.uri;\n if (seen.has(uri)) {\n continue;\n }\n seen.add(uri);\n added.push(ref);\n\n // Only resolve target if available (has target or resolver).\n if (ref.isAvailable) {\n const target = ref.target;\n if (target) {\n next.push(target);\n }\n }\n }\n\n return { added, next };\n }\n\n /**\n * Reduce results into sets of skills and objects.\n */\n private _reduce(items: Binding[]): Bindings {\n return Function.pipe(\n items,\n EArray.reduce(new Bindings(), (context, { skills, objects }) => {\n skills.added.forEach((ref) => context.skills.add(ref));\n skills.removed.forEach((ref) => context.skills.delete(ref));\n\n objects.added.forEach((ref) => context.objects.add(ref));\n objects.removed.forEach((ref) => {\n for (const obj of context.objects) {\n if (\n obj.uri === ref.uri ||\n (EID.tryParse(obj.uri) &&\n EID.tryParse(ref.uri) &&\n EID.getEntityId(EID.tryParse(obj.uri)!) === EID.getEntityId(EID.tryParse(ref.uri)!))\n ) {\n context.objects.delete(obj);\n }\n }\n });\n\n return context;\n }),\n );\n }\n\n /**\n * Merge resolved items into the current set, adding only items not already present (by DXN).\n */\n private _mergeInto<T extends Obj.Unknown>(current: T[], resolved: T[]): T[] {\n const seen = new Set(current.map((obj) => Obj.getURI(obj)));\n const merged = [...current];\n for (const obj of resolved) {\n const uri = Obj.getURI(obj);\n if (!seen.has(uri)) {\n seen.add(uri);\n merged.push(obj);\n }\n }\n return merged;\n }\n\n /**\n * Resolve references to objects, loading them first if needed and falling back to existing objects.\n * DXN refs (e.g. `dxn:org.dxos.skill.database`) resolve via the wired-up ECHO ref resolver\n * which already spans both the space DB and the hypergraph registry.\n */\n private async _resolve<T extends Obj.Unknown>(refs: Iterable<Ref.Ref<T>>, current: T[]): Promise<T[]> {\n const refArray = [...refs];\n\n // Load all refs that need loading.\n await Promise.all(refArray.map((ref) => ref.tryLoad()));\n\n return refArray\n .map((ref) => {\n let target: T | undefined;\n // Only resolve target if available (has target or resolver).\n if (ref.isAvailable) {\n target = ref.target;\n }\n\n // Fallback to existing object.\n return target ?? current.find((obj) => Obj.getURI(obj) === ref.uri);\n })\n .filter(isNonNullable);\n }\n}\n","//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport { DXN, Feed, Obj, Ref, Type } from '@dxos/echo';\n\n/**\n * Feed-level record that links this session to a point in another session's history.\n * When present in a feed, the messages from the referenced feed up to and including\n * `messageId` are prepended to the conversation history before each turn.\n */\nexport class SessionLink extends Type.makeObject<SessionLink>(DXN.make('org.dxos.type.sessionLink', '0.1.0'))(\n Schema.Struct({\n /** Reference to the feed of the source session. */\n feedRef: Ref.Ref(Feed.Feed),\n /** Messages from the source feed up to and including this message ID are injected. */\n messageId: Obj.ID,\n }),\n) {}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\n\nimport { Database, Feed, Filter, Obj } from '@dxos/echo';\nimport { Message } from '@dxos/types';\n\nimport * as SessionLink from './SessionLink';\n\n/**\n * Loads and reifies conversation history by resolving SessionLink feed records.\n */\nexport class SessionLoader {\n /**\n * Prepends linked history to `messages` when the feed contains a SessionLink.\n * Queries the feed for any SessionLink record; if found, loads messages from\n * the referenced feed up to and including `messageId` and prepends them.\n */\n reifyHistory(\n feed: Feed.Feed,\n messages: Message.Message[],\n ): Effect.Effect<Message.Message[], never, Database.Service> {\n return Effect.gen(function* () {\n const links = yield* Feed.query(feed, Filter.type(SessionLink.SessionLink)).run;\n const sessionLinks = links.filter(Obj.instanceOf(SessionLink.SessionLink));\n\n const link = sessionLinks[0];\n if (!link) {\n return messages;\n }\n\n const sourceFeed = link.feedRef.target;\n if (!sourceFeed) {\n return messages;\n }\n\n const sourceMessages = yield* Feed.query(sourceFeed, Filter.type(Message.Message)).run;\n const filtered = sourceMessages.filter(Obj.instanceOf(Message.Message));\n\n // Sort by creation timestamp so history is in chronological order.\n const sorted = [...filtered].sort((a, b) => a.created.localeCompare(b.created));\n\n // Include messages up to and including the fork point.\n const cutoffIndex = sorted.findIndex((m) => m.id === link.messageId);\n if (cutoffIndex < 0) {\n // Fork point not found; return original messages unmodified to avoid injecting unexpected history.\n return messages;\n }\n\n return [...sorted.slice(0, cutoffIndex + 1), ...messages];\n });\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as RpcClient from '@effect/rpc/RpcClient';\nimport * as Context from 'effect/Context';\nimport * as DateTime from 'effect/DateTime';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport type * as Runtime from 'effect/Runtime';\nimport type * as Scope from 'effect/Scope';\n\nimport { LayerSpec, Process, ServiceNotAvailableError } from '@dxos/compute';\nimport { ProcessManager } from '@dxos/compute-runtime';\nimport { Annotation, Database, EID, Feed, Filter, Obj, type URI } from '@dxos/echo';\nimport { EffectEx } from '@dxos/effect';\nimport { BaseError } from '@dxos/errors';\nimport { type ContentBlock, Message } from '@dxos/types';\n\nimport * as AiContext from './AiContext';\nimport { type HarnessControlRpcs } from './harness-control';\nimport { SessionLoader } from './SessionLoader';\n\nexport interface Service {\n /** The conversation {@link AiContext.Binder} (Tier A). */\n binder: Effect.Effect<AiContext.Binder, NotSupportedError>;\n /** The conversation message history (Tier A). */\n history: Effect.Effect<Message.Message[], NotSupportedError>;\n /** Objects bound to the conversation that match the filter (Tier A). */\n queryContext<T extends Obj.Unknown>(filter: Filter.Filter<T>): Effect.Effect<T[], NotSupportedError>;\n /** Enqueue a message into the owning host's input queue (Tier B). */\n enqueueMessage(options: EnqueueMessageOptions): Effect.Effect<void, NotSupportedError>;\n /** Schedule a self-wake on the owning host (Tier B). */\n setAlarm(options: SetAlarmOptions): Effect.Effect<void, NotSupportedError>;\n}\n\n/**\n * Provides access to the controlling harness for tools and operations that are executed by the agent.\n *\n * Replaces AiContextService and AiSessionService.\n */\nexport class HarnessService extends Context.Tag('@dxos/assistant/HarnessService')<HarnessService, Service>() {}\n\n/**\n * Acess current context binder.\n */\nexport const binder: Effect.Effect<AiContext.Binder, NotSupportedError, HarnessService> = Effect.flatMap(\n HarnessService,\n (service) => service.binder,\n);\n\n/**\n * Query the context using a filter.\n */\nexport const queryContext = <T extends Obj.Unknown>(\n filter: Filter.Filter<T>,\n): Effect.Effect<T[], NotSupportedError, HarnessService> =>\n Effect.flatMap(HarnessService, (service) => service.queryContext(filter));\n\ninterface EnqueueMessageOptions {\n content: ContentBlock.Any[];\n\n // TODO(dmaretskyi): Order: 'first' | 'last'\n}\n\n/**\n * Query the session history.\n */\nexport const history: Effect.Effect<Message.Message[], NotSupportedError, HarnessService> = Effect.flatMap(\n HarnessService,\n (service) => service.history,\n);\n\n/**\n * Enqueue a message to the harness.\n */\nexport const enqueueMessage = (\n options: EnqueueMessageOptions,\n): Effect.Effect<void, NotSupportedError, HarnessService> =>\n Effect.flatMap(HarnessService, (service) => service.enqueueMessage(options));\n\ninterface SetAlarmOptions {\n at: DateTime.DateTime;\n /**\n * Message to send when the alarm fires.\n */\n message: string | null;\n}\n\nexport const setAlarm = (options: SetAlarmOptions): Effect.Effect<void, NotSupportedError, HarnessService> =>\n Effect.flatMap(HarnessService, (service) => service.setAlarm(options));\n\n/**\n * Binds skills and/or objects to the conversation context.\n */\nexport const bindContext = ({\n skills,\n objects,\n}: AiContext.BindingProps): Effect.Effect<void, NotSupportedError, HarnessService> =>\n Effect.gen(function* () {\n const sessionBinder = yield* binder;\n yield* Effect.promise(() => sessionBinder.bind({ skills, objects }));\n });\n\nexport class NotSupportedError extends BaseError.extend('NotSupportedError', 'Operation not supported') {}\n\n/**\n * Process-affinity {@link LayerSpec} that materialises {@link HarnessService} from the resolution\n * context's `conversation` DXN. Merges the former `AiContext.Service` (Tier A) with live host\n * dispatch (Tier B).\n */\nexport const layerSpec: LayerSpec.LayerSpec = LayerSpec.make(\n {\n affinity: 'process',\n requires: [Database.Service, ProcessManager.Service],\n provides: [HarnessService],\n },\n (context) =>\n Layer.scoped(\n HarnessService,\n Effect.gen(function* () {\n if (!context.conversation) {\n // LayerSpec.make requires a never-failing layer (error channel = never), so typed failure\n // is not possible here. Die with ServiceNotAvailableError to signal a programming error\n // (missing 'conversation' in spawn environment) that callers cannot recover from.\n return yield* Effect.die(\n new ServiceNotAvailableError(HarnessService.key, {\n message: `Service not available: ${HarnessService.key} — process spawn is missing 'conversation' in environment (set via Operation.withInvocationOptions or ProcessManager.spawn environment)`,\n }),\n );\n }\n const conversation = context.conversation;\n const processManager = yield* ProcessManager.Service;\n const runtime = yield* Effect.runtime<Database.Service>();\n return yield* make({ conversation, processManager, runtime });\n }),\n ),\n);\n\ninterface MakeOptions {\n conversation: URI.URI;\n processManager: Context.Tag.Service<ProcessManager.Service>;\n runtime: Runtime.Runtime<Database.Service>;\n}\n\n/**\n * Builds the {@link Service} for a conversation-scoped resolution context. Tier A resolves the\n * conversation feed / {@link AiContext.Binder} once; Tier B looks up the owning host process lazily per call\n * and dispatches over its `Handle.rpc` control surface (raising {@link NotSupportedError} when no\n * live host owns the conversation).\n */\nexport const make = ({\n conversation,\n processManager,\n runtime,\n}: MakeOptions): Effect.Effect<Service, never, Scope.Scope> =>\n Effect.gen(function* () {\n const feed = yield* Database.resolve(EID.parse(conversation), Feed.Feed).pipe(\n Effect.provide(runtime),\n Effect.orDie,\n );\n const boundBinder = yield* EffectEx.acquireReleaseResource(() => new AiContext.Binder({ feed, runtime }));\n return makeService({\n feed,\n runtime,\n binder: boundBinder,\n owningHost: lookupOwningHost(processManager, conversation),\n });\n });\n\ninterface FromBinderOptions {\n feed: Feed.Feed;\n runtime: Runtime.Runtime<Database.Service>;\n binder: AiContext.Binder;\n}\n\n/**\n * Builds the {@link Service} from a {@link AiContext.Binder} already opened for the conversation (e.g. the\n * agent's own turn fiber, which has no `ProcessManager.Service` in scope). Tier A is fully served;\n * Tier B raises {@link NotSupportedError} since the live-host control surface is not reachable here.\n */\nexport const fromBinder = ({ feed, runtime, binder }: FromBinderOptions): Service =>\n makeService({ feed, runtime, binder, owningHost: Effect.fail(new NotSupportedError()) });\n\ninterface MakeServiceOptions {\n feed: Feed.Feed;\n runtime: Runtime.Runtime<Database.Service>;\n binder: AiContext.Binder;\n owningHost: Effect.Effect<RpcClient.RpcClient<HarnessControlRpcs>, NotSupportedError>;\n}\n\nconst makeService = ({ feed, runtime, binder, owningHost }: MakeServiceOptions): Service => ({\n binder: Effect.succeed(binder),\n history: Effect.gen(function* () {\n const messages = yield* Feed.query(feed, Filter.type(Message.Message)).run;\n return yield* new SessionLoader().reifyHistory(feed, messages);\n }).pipe(Effect.provide(runtime)),\n queryContext: <T extends Obj.Unknown>(filter: Filter.Filter<T>) =>\n Effect.sync(() => {\n const match = Filter.toPredicate(filter);\n return binder.getObjects().filter(match);\n }),\n enqueueMessage: ({ content }) => owningHost.pipe(Effect.flatMap((rpc) => rpc.enqueueMessage({ content }))),\n setAlarm: ({ at, message }) =>\n owningHost.pipe(Effect.flatMap((rpc) => rpc.setAlarm({ at: DateTime.toUtc(at), message }))),\n});\n\n/**\n * Resolves the live host owning `conversation` per call (so a process replacement — e.g. a model\n * switch — is never captured stale) and exposes its `HarnessControl` RPC client.\n */\nconst lookupOwningHost = (\n processManager: Context.Tag.Service<ProcessManager.Service>,\n conversation: URI.URI,\n): Effect.Effect<RpcClient.RpcClient<HarnessControlRpcs>, NotSupportedError> =>\n Effect.gen(function* () {\n const processes = yield* processManager.list({ target: conversation });\n const host = processes.find(\n (process) =>\n !isTerminalProcess(process.status.state) &&\n Option.getOrElse(\n Annotation.getDictionary(process.params.annotations, Process.HarnessHostAnnotation),\n () => false,\n ),\n );\n if (!host) {\n return yield* Effect.fail(new NotSupportedError());\n }\n // The host is discovered by annotation, but the HarnessControl RPC contract is fixed at the\n // spawn site (agent-process declares it as its `rpcs`); narrow the variance-erased\n // `RpcClient<any>` to that contract so the dispatch below is typed. No typed path exists here:\n // the host handle carries `RpcClient<any>` (design spec §4.4) and the concrete definition lives\n // in `@dxos/functions-runtime`, which depends on this package — importing it would cycle.\n return host.rpc as unknown as RpcClient.RpcClient<HarnessControlRpcs>;\n });\n\nconst isTerminalProcess = (state: Process.State): boolean =>\n state === Process.State.SUCCEEDED || state === Process.State.FAILED || state === Process.State.TERMINATED;\n","//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Effect from 'effect/Effect';\n\nimport { Operation, Skill } from '@dxos/compute';\nimport { Database, Obj } from '@dxos/echo';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\n/**\n * Tag of the lifecycle point a hook fires at, matching {@link Skill.HookSpec}.\n */\nexport type HookPhase = 'begin-request' | 'end-request';\n\n/**\n * Invokes a resolved operation with the hook's templated input. Begin and end hooks fire in\n * different contexts (the agent's turn fiber vs. a child process with Tier B reachable), so the\n * invocation strategy is supplied by the caller rather than fixed here. `R` carries the invoker's\n * own requirements (e.g. `Operation.Service`) up into {@link runHooks}.\n */\nexport type HookInvoker<R> = (\n operation: Operation.Definition.Any,\n input: Record<string, unknown>,\n) => Effect.Effect<void, never, R>;\n\n/**\n * Runs every {@link Skill.Hook} on `skills` whose spec matches `phase`. Each hook resolves its\n * `function` ref to a {@link Operation.PersistentOperation}, deserializes it to a definition, and\n * invokes it with the templated `input` via `invoke`. Hooks without a function ref are skipped.\n *\n * Hook failures are isolated: a throwing hook logs and is swallowed so one skill's hook cannot\n * abort the request lifecycle (or the sibling hooks).\n */\nexport const runHooks = <R>({\n skills,\n phase,\n invoke,\n}: {\n skills: readonly Skill.Skill[];\n phase: HookPhase;\n invoke: HookInvoker<R>;\n}): Effect.Effect<void, never, Database.Service | R> =>\n Effect.gen(function* () {\n for (const skill of skills) {\n for (const hook of skill.hooks ?? []) {\n if (hook.spec._tag !== phase) {\n continue;\n }\n if (!hook.function) {\n continue;\n }\n\n yield* Effect.gen(function* () {\n const record = yield* Database.load(hook.function!);\n invariant(Obj.instanceOf(Operation.PersistentOperation, record), 'Hook function must be an operation.');\n const operation = Operation.deserialize(record);\n // Hooks carry no event payload (the spec is a bare tag), so the input template is passed\n // through verbatim — the hook's operation reads any conversation state it needs itself.\n yield* invoke(operation, { ...hook.input });\n }).pipe(\n Effect.catchAllCause((cause) =>\n Effect.sync(() => log.warn('skill hook failed', { phase, skill: Skill.getKey(skill), cause })),\n ),\n );\n }\n }\n });\n","//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { type Registry as AtomRegistry } from '@effect-atom/atom';\nimport * as Array from 'effect/Array';\nimport * as Effect from 'effect/Effect';\nimport * as Either from 'effect/Either';\nimport { pipe } from 'effect/Function';\nimport * as Layer from 'effect/Layer';\nimport * as Order from 'effect/Order';\nimport * as Record from 'effect/Record';\nimport * as Runtime from 'effect/Runtime';\n\nimport { type OpaqueToolkit, type ToolExecutionService, type ToolResolverService } from '@dxos/ai';\nimport { type Instructions, McpServer, Operation, type Skill, Trace } from '@dxos/compute';\nimport { Resource } from '@dxos/context';\nimport { Database, Feed, Filter, Obj, Registry } from '@dxos/echo';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { McpToolkit } from '@dxos/mcp-client';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { type ContentBlock, Message } from '@dxos/types';\n\nimport { AiRequest, type GenerationObserver, formatSystemPrompt } from '../request';\nimport { ToolExecutionServices } from '../tool-runtime';\nimport { McpServerError } from '../util';\nimport * as AiContext from './AiContext';\nimport * as Harness from './Harness';\nimport { SessionLoader } from './SessionLoader';\nimport * as SkillHooks from './SkillHooks';\nimport { createToolkit } from './toolkit';\n\nexport type RunProps<R = never> = {\n prompt: string | ContentBlock.Any[];\n system?: string;\n observer?: GenerationObserver;\n toolkit?: OpaqueToolkit.OpaqueToolkit<R>;\n\n /**\n * Space-level MCP servers to connect alongside skill-defined ones.\n */\n mcpServers?: readonly McpServer.McpServer[];\n\n /**\n * When false, messages from this request are not appended to the feed or persisted to trace.\n *\n * @default true\n */\n persist?: boolean;\n};\n\nexport type Options = {\n feed: Feed.Feed;\n runtime: Runtime.Runtime<Database.Service>;\n /** @effect-atom/atom-react Registry for reactive state. */\n registry?: AtomRegistry.Registry;\n /**\n * Instructions steering the conversation (typically the owning `Chat`'s), rendered into the system\n * prompt on every turn. The session is feed-centric and cannot reach its chat, so these are passed in.\n */\n instructions?: readonly Instructions.Instructions[];\n};\n\n/**\n * Summarization threshold in tokens.\n */\n// TODO(dmaretskyi): Take from model characteristics. opus has 200k max tokens.\nconst SUMMARY_THRESHOLD = 80_000;\n\n/**\n * Durable conversation state (initiated by users and agents) backed by a Feed.\n * Executes tools based on AI responses and supports cancellation of in-progress requests.\n */\nexport class Session extends Resource {\n private readonly _feed: Feed.Feed;\n private readonly _runtime: Runtime.Runtime<Database.Service>;\n readonly #instructions: readonly Instructions.Instructions[];\n\n /**\n * Skills and objects bound to the session.\n */\n private readonly _binder: AiContext.Binder;\n\n private readonly _sessionLoader = new SessionLoader();\n\n public constructor(options: Options) {\n super();\n this._feed = options.feed;\n this._runtime = options.runtime;\n this.#instructions = options.instructions ?? [];\n invariant(this._feed);\n invariant(this._runtime);\n this._binder = new AiContext.Binder({\n feed: this._feed,\n runtime: this._runtime,\n registry: options.registry,\n });\n }\n\n protected override async _open(): Promise<void> {\n await this._binder.open(this._ctx);\n }\n\n public get feed() {\n return this._feed;\n }\n\n public get context() {\n return this._binder;\n }\n\n /**\n * The conversation as the model should see it: only the messages reachable from the feed's current\n * head, so a soft fork's abandoned turns are excluded.\n */\n public async getHistory(): Promise<Message.Message[]> {\n const { items: reachable } = Feed.history(await this.#messagesInAppendOrder());\n return Runtime.runPromise(this._runtime)(this._sessionLoader.reifyHistory(this._feed, reachable));\n }\n\n /**\n * Every message in the feed, in append order — what `Feed.history` needs, since it walks lineage\n * positionally rather than by `created`, a wall clock peers do not agree on.\n */\n async #messagesInAppendOrder(): Promise<Message.Message[]> {\n const queryResult = await Runtime.runPromise(this._runtime)(Feed.query(this._feed, Filter.type(Message.Message)));\n const items = await queryResult.run();\n return Array.sort(items.filter(Obj.instanceOf(Message.Message)), byFeedPosition);\n }\n\n getTools(): Effect.Effect<\n Record<string, import('@effect/ai/Tool').Any>,\n never,\n ToolExecutionService | ToolResolverService\n > {\n return Effect.gen(this, function* () {\n const toolkit = yield* createToolkit({ skills: this.context.getSkills() });\n return toolkit.toolkit.tools;\n }).pipe(Effect.orDie);\n }\n\n /**\n * Not provided by default, since users might want to override them.\n */\n makeToolExecutionServices(): Layer.Layer<\n ToolExecutionService | ToolResolverService,\n never,\n OpaqueToolkit.OpaqueToolkitProvider | Operation.Service | Registry.Service\n > {\n return ToolExecutionServices.pipe(\n Layer.provide(Operation.withInvocationOptions({ conversation: Obj.getURI(this._feed) })),\n );\n }\n\n /**\n * Appends one of this turn's messages to the feed, consuming a pending rewind if there is one.\n *\n * The rewind decision is made in the UI, but the continuation is appended by the agent's process,\n * which resolves the feed and never sees the chat — so the feed carries the intent and this is where\n * it becomes lineage. `rewindFrom` names the earliest discarded message, so the new parent is whatever\n * precedes it; nothing preceding means the continuation starts a fresh line. Only the first message of\n * a turn finds it set, since the append clears it, so the rest of the turn chains implicitly. Clearing\n * after the append (rather than before) leaves the rewind pending if the turn fails.\n */\n public async appendTurnMessage(message: Message.Message): Promise<void> {\n const rewindFrom = this._feed.rewindFrom;\n const parent = rewindFrom !== undefined ? await this.#parentForRewind(rewindFrom) : undefined;\n\n return Runtime.runPromise(this._runtime)(\n Effect.gen(this, function* () {\n yield* Feed.append(this._feed, [message], parent !== undefined ? { parent } : undefined);\n if (rewindFrom !== undefined) {\n Obj.update(this._feed, (feed) => {\n feed.rewindFrom = undefined;\n });\n }\n }),\n );\n }\n\n /** The message preceding `rewindFrom` in append order, which the continuation parents to. */\n async #parentForRewind(rewindFrom: string): Promise<string | undefined> {\n const messages = await this.#messagesInAppendOrder();\n const index = messages.findIndex((message) => message.id === rewindFrom);\n return index > 0 ? messages[index - 1].id : undefined;\n }\n\n /**\n * Creates a new cancelable request effect.\n */\n public createRequest<R = never>(\n params: RunProps<R>,\n ): Effect.Effect<Message.Message[], AiRequest.RunError, AiRequest.RunRequirements | R> {\n return Effect.gen(this, function* () {\n const history = yield* Effect.promise(() => this.getHistory());\n const skills = this.context.getSkills();\n const objects = this.context.getObjects();\n\n log('run', {\n history: history.length,\n skills: skills.length,\n objects: objects.length,\n });\n\n const request = new AiRequest.Request({\n summarizationThreshold: SUMMARY_THRESHOLD,\n observer: params.observer,\n persist: params.persist,\n onOutput: (message) => Effect.promise(() => this.appendTurnMessage(message)),\n });\n\n yield* request.begin({\n history,\n skills,\n objects,\n instructions: this.#instructions,\n prompt: params.prompt,\n system: params.system,\n });\n\n // Fire begin-request hooks declared by the bound skills. These run in the agent's turn\n // fiber (Tier A only), so they cannot reach the live host (Tier B) — that is the end hook's job.\n yield* SkillHooks.runHooks({\n skills,\n phase: 'begin-request',\n invoke: (operation, input) => Operation.invoke(operation, input).pipe(Effect.asVoid, Effect.orDie),\n });\n\n // Turn loop: recompute toolkit and system prompt between turns to pick up dynamically enabled skills.\n do {\n yield* Effect.promise(() => this.context.sync());\n const currentSkills = this.context.getSkills();\n const mcps = yield* connectMcpServers(currentSkills, params.mcpServers);\n const toolkit = yield* createToolkit({\n toolkit: params.toolkit,\n skills: currentSkills,\n opaqueToolkits: mcps,\n });\n\n log('toolkit', { tools: Record.keys(toolkit.toolkit.tools) });\n const system = yield* formatSystemPrompt({\n system: params.system,\n skills: currentSkills,\n objects: this.context.getObjects(),\n instructions: this.#instructions,\n }).pipe(Effect.orDie);\n\n const { done, finishReason } = yield* request.runAgentTurn({ system, toolkit });\n if (done) {\n break;\n }\n // A paused server-tool turn (e.g. Anthropic `pause_turn`) resumes with another request and\n // no local tool execution; the trailing server tool call must be left intact for the provider.\n if (finishReason === 'pause') {\n continue;\n }\n\n yield* request.runTools({ toolkit });\n } while (true);\n\n log('result', {\n messages: request.pending.length,\n duration: request.duration,\n toolCalls: request.toolCalls,\n });\n\n return [...request.pending];\n }).pipe(\n Effect.provide(\n Layer.mergeAll(\n // Tier A only: the agent's own turn fiber has no `ProcessManager.Service` in scope, so\n // Tier B (setAlarm/enqueueMessage) is reachable only by child operations through the\n // process-affinity HarnessService LayerSpec — not from here.\n Layer.succeed(\n Harness.HarnessService,\n Harness.fromBinder({ feed: this._feed, runtime: this._runtime, binder: this.context }),\n ),\n Operation.withInvocationOptions({ conversation: Obj.getURI(this._feed) }),\n ),\n ),\n Effect.withSpan('AiSession.createRequest'),\n );\n }\n}\n\nconst connectMcpServers = (\n skills: readonly Skill.Skill[],\n spaceMcpServers: readonly McpServer.McpServer[] = [],\n): Effect.Effect<OpaqueToolkit.OpaqueToolkit[], never, Trace.TraceService> => {\n const skillServers: McpToolkit.McpToolkitOptions[] = pipe(\n skills,\n Array.flatMap((_) => _.mcpServers ?? []),\n Array.map(({ url, protocol, apiKey }) => ({ url, protocol, apiKey })),\n );\n const spaceServers: McpToolkit.McpToolkitOptions[] = spaceMcpServers.map(({ url, protocol, apiKey }) => ({\n url,\n protocol,\n apiKey,\n }));\n const allServers = [...skillServers, ...spaceServers];\n\n return pipe(\n allServers,\n Effect.forEach((options) =>\n McpToolkit.make(options).pipe(\n // NOTE: Type-inference fails here without explicit void return.\n Effect.tap((toolkit): void =>\n log.info('Connected to MCP server', { url: options.url, tools: Object.keys(toolkit.toolkit.tools).length }),\n ),\n // Surface typed connection failures via ephemeral trace + warn log, then drop the server.\n Effect.tapError((error) =>\n Effect.gen(function* () {\n log.warn('Failed to connect to MCP server', {\n url: error.url,\n protocol: error.protocol,\n message: error.message,\n });\n yield* Trace.write(McpServerError, {\n url: error.url,\n protocol: error.protocol,\n message: error.message,\n });\n }),\n ),\n // Catch unexpected defects too (e.g. malformed tool schemas) so a single broken\n // server can never abort the whole turn — surface them through the same channel.\n Effect.catchAllDefect((defect) =>\n Effect.gen(function* () {\n const message = defect instanceof Error ? defect.message : String(defect);\n log.warn('Unexpected MCP defect', { url: options.url, message });\n yield* Trace.write(McpServerError, {\n url: options.url,\n protocol: options.protocol,\n message: `Unexpected MCP failure: ${message}`,\n });\n return yield* Effect.fail(\n new McpToolkit.McpConnectionError({\n url: options.url,\n protocol: options.protocol,\n message,\n }),\n );\n }),\n ),\n Effect.either,\n ),\n ),\n Effect.map(Array.filterMap((_) => Either.getRight(_))),\n );\n};\n\n/**\n * Orders feed items by the position the server assigned them. Unpositioned blocks (written locally and\n * not yet acknowledged) sort last, which is what we want: a message just written is the newest.\n */\nconst byFeedPosition = Order.make<Message.Message>((a, b) => {\n const positionA = feedPosition(a);\n const positionB = feedPosition(b);\n return positionA === positionB ? 0 : positionA < positionB ? -1 : 1;\n});\n\nconst feedPosition = (message: Message.Message): number => {\n const key = Obj.getKeys(message, FeedProtocol.KEY_QUEUE_POSITION).at(0)?.id;\n const position = key !== undefined ? Number(key) : Number.NaN;\n return Number.isNaN(position) ? Number.POSITIVE_INFINITY : position;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Rpc from '@effect/rpc/Rpc';\nimport * as RpcGroup from '@effect/rpc/RpcGroup';\nimport * as Schema from 'effect/Schema';\n\nimport { ContentBlock } from '@dxos/types';\n\n/**\n * Typed control surface on the live host process that owns a conversation's harness.\n *\n * The same group is declared as the agent process's `rpcs` (so its handlers run on the host's\n * server fiber with the live `AlarmManager`/`inputQueue` in scope) and used by {@link HarnessService}\n * Tier B to dispatch over the discovered host's `Handle.rpc` — keeping both ends on one contract.\n */\nexport const HarnessControl = RpcGroup.make(\n Rpc.make('setAlarm', {\n payload: Schema.Struct({ at: Schema.DateTimeUtc, message: Schema.NullOr(Schema.String) }),\n success: Schema.Void,\n }),\n Rpc.make('enqueueMessage', {\n payload: Schema.Struct({ content: Schema.Array(ContentBlock.Any) }),\n success: Schema.Void,\n }),\n);\n\n/** Union of the RPCs declared in {@link HarnessControl}. */\nexport type HarnessControlRpcs = RpcGroup.Rpcs<typeof HarnessControl>;\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport defaultsDeep from 'lodash.defaultsdeep';\n\nimport { Model } from '@dxos/ai';\nimport { Template } from '@dxos/compute';\n// Text is referenced in the inferred type of 'templates' (via Template.make → Template.Template.source → Ref.Ref(Text.Text));\n// the import lets TypeScript name it in the emitted .d.ts.\n// eslint-disable-next-line unused-imports/no-unused-imports\nimport { type Text } from '@dxos/schema';\n\nimport FORMAT from './instructions/format.tpl?raw';\nimport SYSTEM from './instructions/system.tpl?raw';\n\n/**\n * System template variables.\n */\nexport type SystemPromptOptions = Model.Capabilities & {\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\n/**\n * NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.\n */\nconst SYSTEM_ID = '01K2J2FZWH39F55CS7B26GP1Q3';\n\nexport const templates = {\n system: Template.make({\n id: SYSTEM_ID,\n source: SYSTEM,\n }),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,IA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,QAAQ;AACV,CAAC,EACH"}
|
|
@@ -2,7 +2,7 @@ import type * as AiError from '@effect/ai/AiError';
|
|
|
2
2
|
import * as LanguageModel from '@effect/ai/LanguageModel';
|
|
3
3
|
import * as Effect from 'effect/Effect';
|
|
4
4
|
import { type AiToolNotFoundError, type OpaqueToolkit, type PromptPreprocessingError, type ToolExecutionService, type ToolResolverService } from '@dxos/ai';
|
|
5
|
-
import { Operation, type Skill, Trace } from '@dxos/compute';
|
|
5
|
+
import { type Instructions, Operation, type Skill, Trace } from '@dxos/compute';
|
|
6
6
|
import { Database, Obj, Registry } from '@dxos/echo';
|
|
7
7
|
import { ContentBlock, Message } from '@dxos/types';
|
|
8
8
|
import { type AiAssistantError } from '../util';
|
|
@@ -33,6 +33,8 @@ export type RunProps<R = never> = {
|
|
|
33
33
|
history?: Message.Message[];
|
|
34
34
|
objects?: Obj.Unknown[];
|
|
35
35
|
skills?: readonly Skill.Skill[];
|
|
36
|
+
/** Rendered inline into the system prompt; passed explicitly rather than inferred from `objects`. */
|
|
37
|
+
instructions?: readonly Instructions.Instructions[];
|
|
36
38
|
toolkit?: OpaqueToolkit.OpaqueToolkit<R>;
|
|
37
39
|
};
|
|
38
40
|
export type BeginProps = {
|
|
@@ -41,6 +43,7 @@ export type BeginProps = {
|
|
|
41
43
|
history?: Message.Message[];
|
|
42
44
|
objects?: Obj.Unknown[];
|
|
43
45
|
skills?: readonly Skill.Skill[];
|
|
46
|
+
instructions?: readonly Instructions.Instructions[];
|
|
44
47
|
};
|
|
45
48
|
export type TurnProps<R = never> = {
|
|
46
49
|
system: string;
|
|
@@ -102,7 +105,7 @@ export declare class Request {
|
|
|
102
105
|
* Initialize a session: set up history, perform summarization if needed, and submit the user prompt.
|
|
103
106
|
* Must be called before `runTurn()`.
|
|
104
107
|
*/
|
|
105
|
-
begin: ({ prompt, system, history, skills, objects, }: BeginProps) => Effect.Effect<void, RunError, RunRequirements>;
|
|
108
|
+
begin: ({ prompt, system, history, skills, objects, instructions, }: BeginProps) => Effect.Effect<void, RunError, RunRequirements>;
|
|
106
109
|
/**
|
|
107
110
|
* Execute a single turn: one LLM generation followed by tool execution.
|
|
108
111
|
* The toolkit and system prompt can be updated between turns to reflect context changes (e.g. dynamically enabled skills).
|
|
@@ -114,6 +117,6 @@ export declare class Request {
|
|
|
114
117
|
/**
|
|
115
118
|
* Run a full conversation turn loop. Equivalent to calling `begin()` then `runTurn()` in a loop.
|
|
116
119
|
*/
|
|
117
|
-
run: <const R = never>({ prompt, system: systemTemplate, history, objects, skills, toolkit, }: RunProps<R>) => Effect.Effect<Message.Message[], RunError, RunRequirements | R>;
|
|
120
|
+
run: <const R = never>({ prompt, system: systemTemplate, history, objects, skills, instructions, toolkit, }: RunProps<R>) => Effect.Effect<Message.Message[], RunError, RunRequirements | R>;
|
|
118
121
|
}
|
|
119
122
|
//# sourceMappingURL=AiRequest.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiRequest.d.ts","sourceRoot":"","sources":["../../../../src/request/AiRequest.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,OAAO,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,aAAa,MAAM,0BAA0B,CAAC;AAI1D,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAKxC,OAAO,EAIL,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EAGzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,SAAS,EAAE,KAAK,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"AiRequest.d.ts","sourceRoot":"","sources":["../../../../src/request/AiRequest.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,OAAO,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,aAAa,MAAM,0BAA0B,CAAC;AAI1D,OAAO,KAAK,MAAM,MA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-0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AiRequest.test.d.ts","sourceRoot":"","sources":["../../../../src/request/AiRequest.test.ts"],"names":[],"mappings":""}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import * as Effect from 'effect/Effect';
|
|
2
2
|
import { type FunctionNotFoundError, type Operation } from '@dxos/compute';
|
|
3
|
-
import {
|
|
3
|
+
import { Database, type Registry } from '@dxos/echo';
|
|
4
4
|
import { type EntityNotFoundError } from '@dxos/echo/Err';
|
|
5
5
|
import { Message } from '@dxos/types';
|
|
6
6
|
import type * as AiRequest from './AiRequest';
|
|
7
7
|
/**
|
|
8
8
|
* Formats the system prompt.
|
|
9
9
|
*/
|
|
10
|
-
export declare const formatSystemPrompt: ({ system, skills, objects, }: Pick<AiRequest.RunProps, 'system' | 'skills' | 'objects'>) => Effect.Effect<string, FunctionNotFoundError | EntityNotFoundError, Database.Service | Registry.Service | Operation.Service>;
|
|
10
|
+
export declare const formatSystemPrompt: ({ system, skills, objects, instructions, }: Pick<AiRequest.RunProps, 'system' | 'skills' | 'objects' | 'instructions'>) => Effect.Effect<string, FunctionNotFoundError | EntityNotFoundError, Database.Service | Registry.Service | Operation.Service>;
|
|
11
11
|
/**
|
|
12
12
|
* Formats the user prompt.
|
|
13
13
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../../src/request/format.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC,OAAO,EAAE,KAAK,qBAAqB,EAAE,KAAK,SAAS,EAAY,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../../src/request/format.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC,OAAO,EAAE,KAAK,qBAAqB,EAAE,KAAK,SAAS,EAAY,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,QAAQ,EAAO,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,KAAK,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAG1D,OAAO,EAAqB,OAAO,EAAE,MAAM,aAAa,CAAC;AAIzD,OAAO,KAAK,KAAK,SAAS,MAAM,aAAa,CAAC;AAG9C;;GAEG;AAEH,eAAO,MAAM,kBAAkB,+CAK5B,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,cAAc,CAAC,KAAG,MAAM,CAAC,MAAM,CAC3F,MAAM,EACN,qBAAqB,GAAG,mBAAmB,EAC3C,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,GAAG,SAAS,CAAC,OAAO,CAyET,CAAC;AAEjD;;GAEG;AAGH,eAAO,MAAM,gBAAgB,yBAG1B,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC,KAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC,QAAQ,CAoCvD,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.test.d.ts","sourceRoot":"","sources":["../../../../src/request/format.test.ts"],"names":[],"mappings":""}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Atom, Registry as AtomRegistry } from '@effect-atom/atom
|
|
1
|
+
import { Atom, Registry as AtomRegistry } from '@effect-atom/atom';
|
|
2
2
|
import * as Runtime from 'effect/Runtime';
|
|
3
3
|
import { Skill } from '@dxos/compute';
|
|
4
4
|
import { Resource } from '@dxos/context';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiContext.d.ts","sourceRoot":"","sources":["../../../../src/session/AiContext.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,YAAY,EAAE,MAAM,
|
|
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IAAI,CAAC,CAsC7D;IAED;;OAEG;IACH,OAAO,CAAC,gBAAgB;IA+BxB;;OAEG;IACH,OAAO,CAAC,OAAO;IA0Bf;;OAEG;IACH,OAAO,CAAC,UAAU;YAkBJ,QAAQ;CAmBvB"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { type Registry as AtomRegistry } from '@effect-atom/atom
|
|
1
|
+
import { type Registry as AtomRegistry } from '@effect-atom/atom';
|
|
2
2
|
import * as Effect from 'effect/Effect';
|
|
3
3
|
import * as Layer from 'effect/Layer';
|
|
4
4
|
import * as Runtime from 'effect/Runtime';
|
|
5
5
|
import { type OpaqueToolkit, type ToolExecutionService, type ToolResolverService } from '@dxos/ai';
|
|
6
|
-
import { McpServer, Operation } from '@dxos/compute';
|
|
6
|
+
import { type Instructions, McpServer, Operation } from '@dxos/compute';
|
|
7
7
|
import { Resource } from '@dxos/context';
|
|
8
8
|
import { Database, Feed, Registry } from '@dxos/echo';
|
|
9
9
|
import { type ContentBlock, Message } from '@dxos/types';
|
|
@@ -30,29 +30,50 @@ export type Options = {
|
|
|
30
30
|
runtime: Runtime.Runtime<Database.Service>;
|
|
31
31
|
/** @effect-atom/atom-react Registry for reactive state. */
|
|
32
32
|
registry?: AtomRegistry.Registry;
|
|
33
|
+
/**
|
|
34
|
+
* Instructions steering the conversation (typically the owning `Chat`'s), rendered into the system
|
|
35
|
+
* prompt on every turn. The session is feed-centric and cannot reach its chat, so these are passed in.
|
|
36
|
+
*/
|
|
37
|
+
instructions?: readonly Instructions.Instructions[];
|
|
33
38
|
};
|
|
34
39
|
/**
|
|
35
40
|
* Durable conversation state (initiated by users and agents) backed by a Feed.
|
|
36
41
|
* Executes tools based on AI responses and supports cancellation of in-progress requests.
|
|
37
42
|
*/
|
|
38
43
|
export declare class Session extends Resource {
|
|
44
|
+
#private;
|
|
45
|
+
private readonly _feed;
|
|
46
|
+
private readonly _runtime;
|
|
39
47
|
/**
|
|
40
48
|
* Skills and objects bound to the session.
|
|
41
49
|
*/
|
|
42
50
|
private readonly _binder;
|
|
43
|
-
private readonly _feed;
|
|
44
|
-
private readonly _runtime;
|
|
45
51
|
private readonly _sessionLoader;
|
|
46
52
|
constructor(options: Options);
|
|
47
53
|
protected _open(): Promise<void>;
|
|
48
54
|
get feed(): Feed.Feed;
|
|
49
55
|
get context(): AiContext.Binder;
|
|
56
|
+
/**
|
|
57
|
+
* The conversation as the model should see it: only the messages reachable from the feed's current
|
|
58
|
+
* head, so a soft fork's abandoned turns are excluded.
|
|
59
|
+
*/
|
|
50
60
|
getHistory(): Promise<Message.Message[]>;
|
|
51
61
|
getTools(): Effect.Effect<Record<string, import('@effect/ai/Tool').Any>, never, ToolExecutionService | ToolResolverService>;
|
|
52
62
|
/**
|
|
53
63
|
* Not provided by default, since users might want to override them.
|
|
54
64
|
*/
|
|
55
65
|
makeToolExecutionServices(): Layer.Layer<ToolExecutionService | ToolResolverService, never, OpaqueToolkit.OpaqueToolkitProvider | Operation.Service | Registry.Service>;
|
|
66
|
+
/**
|
|
67
|
+
* Appends one of this turn's messages to the feed, consuming a pending rewind if there is one.
|
|
68
|
+
*
|
|
69
|
+
* The rewind decision is made in the UI, but the continuation is appended by the agent's process,
|
|
70
|
+
* which resolves the feed and never sees the chat — so the feed carries the intent and this is where
|
|
71
|
+
* it becomes lineage. `rewindFrom` names the earliest discarded message, so the new parent is whatever
|
|
72
|
+
* precedes it; nothing preceding means the continuation starts a fresh line. Only the first message of
|
|
73
|
+
* a turn finds it set, since the append clears it, so the rest of the turn chains implicitly. Clearing
|
|
74
|
+
* after the append (rather than before) leaves the rewind pending if the turn fails.
|
|
75
|
+
*/
|
|
76
|
+
appendTurnMessage(message: Message.Message): Promise<void>;
|
|
56
77
|
/**
|
|
57
78
|
* Creates a new cancelable request effect.
|
|
58
79
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiSession.d.ts","sourceRoot":"","sources":["../../../../src/session/AiSession.ts"],"names":[],"mappings":"AAM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,EAC5B,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAClB,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,QAAQ,EAAE,SAAS,CAAC,eAAe,GAAG,CAAC,CAAC,CA0FrF;CACF"}
|
|
@@ -13,6 +13,10 @@ export declare const HarnessControl: RpcGroup.RpcGroup<Rpc.Rpc<"enqueueMessage",
|
|
|
13
13
|
pending: Schema.optional<typeof Schema.Boolean>;
|
|
14
14
|
objectId: import("@dxos/keys").EntityIdClass;
|
|
15
15
|
version: typeof Schema.Unknown;
|
|
16
|
+
}>, Schema.TaggedStruct<"change", {
|
|
17
|
+
pending: Schema.optional<typeof Schema.Boolean>;
|
|
18
|
+
before: typeof Schema.String;
|
|
19
|
+
after: typeof Schema.String;
|
|
16
20
|
}>, Schema.TaggedStruct<"file", {
|
|
17
21
|
pending: Schema.optional<typeof Schema.Boolean>;
|
|
18
22
|
url: typeof Schema.String;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"harness-control.d.ts","sourceRoot":"","sources":["../../../../src/session/harness-control.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,GAAG,MAAM,iBAAiB,CAAC;AACvC,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AACjD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC;;;;;;GAMG;AACH,eAAO,MAAM,cAAc
|
|
1
|
+
{"version":3,"file":"harness-control.d.ts","sourceRoot":"","sources":["../../../../src/session/harness-control.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,GAAG,MAAM,iBAAiB,CAAC;AACvC,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AACjD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC;;;;;;GAMG;AACH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oDAS1B,CAAC;AAEF,4DAA4D;AAC5D,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC,IAAI,CAAC,OAAO,cAAc,CAAC,CAAC"}
|