import { ProviderPlugin } from '../../lib/providers';
import { ATTACHMENT_TOOLS_PREAMBLE } from '../../lib/attachmentTools';
import { createOllamaChatAgent, OllamaChatAgent } from './chatAgent';
import { ollamaModelDefinition } from './modelDefinition';
import { OllamaRunState, resumeOllamaChatRun, startOllamaChatRun } from './runner';
import { setAttachmentToolDefinitionsResolver } from './attachmentTools';
const assertOllamaAgent = (agent) => {
    if (agent instanceof OllamaChatAgent) {
        return agent;
    }
    throw new Error('Ollama provider received an incompatible agent instance');
};
const TOOL_USE_PREAMBLE = `
Analyze the given prompt and decided whether or not it can be answered by a tool.
If it can, use the following functions to respond with a JSON for a function call with its proper arguments that best answers the given prompt.
Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.
Do not use variables.
`;
const buildInstructions = (options) => {
    return [ATTACHMENT_TOOLS_PREAMBLE, TOOL_USE_PREAMBLE, options.instructions ?? '']
        .filter((segment) => typeof segment === 'string' && segment.trim().length > 0)
        .map((segment) => segment.trim())
        .join('\n\n');
};
const ollamaProvider = {
    metadata: {
        kind: 'ollama',
        name: 'Ollama',
        supportsTools: true,
        supportsApprovals: true,
        supportsStreaming: true,
        isImplemented: true
    },
    createAgent: (options) => createOllamaChatAgent({
        ...options,
        instructions: buildInstructions(options)
    }),
    startRun: async (agent, input, callbacks) => {
        const ollamaAgent = assertOllamaAgent(agent);
        return startOllamaChatRun(ollamaAgent, input, callbacks);
    },
    resumeRun: async (agent, input, callbacks) => {
        const ollamaAgent = assertOllamaAgent(agent);
        return resumeOllamaChatRun(ollamaAgent, input, callbacks);
    },
    deserializeRunState: async (_agent, serialized) => {
        return OllamaRunState.deserialize(serialized);
    }
};
export class OllamaProvider extends ProviderPlugin {
    constructor() {
        super(...arguments);
        Object.defineProperty(this, "id", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'ollama'
        });
    }
    async createProvider() {
        return ollamaProvider;
    }
    async getModelDefinition() {
        return ollamaModelDefinition;
    }
    configureAttachmentTools(resolve) {
        setAttachmentToolDefinitionsResolver(resolve);
    }
}
