@omp-provider-capabilities/mistral 0.0.0-stage → 0.1.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/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@omp-provider-capabilities/mistral",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Mistral provider extension: batch execution, Agents API (code execution, web search).",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "scripts": {
9
+ "build": "tsc --noEmit"
10
+ },
11
+ "dependencies": {
12
+ "@omp-provider-capabilities/core": "^0.1.0"
13
+ },
14
+ "peerDependencies": {
15
+ "@oh-my-pi/pi-coding-agent": "*"
16
+ },
17
+ "omp": {
18
+ "extensions": [
19
+ "./src/index.ts"
20
+ ]
21
+ },
22
+ "files": [
23
+ "src/",
24
+ "!src/**/*.test.ts",
25
+ "package.json"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "keywords": [
31
+ "omp-package",
32
+ "omp-plugin",
33
+ "omp-extension",
34
+ "oh-my-pi"
35
+ ]
36
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Mistral Agent SDK wrapper.
3
+ *
4
+ * Wraps @mistralai/mistralai's Beta.Agents API.
5
+ * Provides agents with built-in connectors (web_search, code_execution,
6
+ * image_gen, MCP), handoffs, and persistent memory.
7
+ */
8
+
9
+ import type {
10
+ AgentSDK,
11
+ AgentConfig,
12
+ AgentResult,
13
+ AgentMessage,
14
+ AgentTool,
15
+ } from "@omp-provider-capabilities/core";
16
+
17
+ /** Map our tool names to Mistral connector types */
18
+ const CONNECTOR_MAP: Record<string, string> = {
19
+ web_search: "web_search",
20
+ code_execution: "code_execution",
21
+ image_gen: "image_gen",
22
+ mcp: "mcp",
23
+ };
24
+
25
+ /**
26
+ * Mistral Agent SDK implementation.
27
+ */
28
+ export class MistralAgentSDK implements AgentSDK {
29
+ public provider = "mistral";
30
+ private apiKey: string;
31
+
32
+ constructor(apiKey: string) {
33
+ this.apiKey = apiKey;
34
+ }
35
+
36
+ isAvailable(): boolean {
37
+ return !!this.apiKey;
38
+ }
39
+
40
+ async run(prompt: string, config: AgentConfig): Promise<AgentResult> {
41
+ const history: AgentMessage[] = [...(config.history || [])];
42
+ let toolCallCount = 0;
43
+ let output = "";
44
+
45
+ try {
46
+ // Try the Mistral SDK first
47
+ // @ts-ignore - optional peer dependency
48
+ const { MistralClient } = await import("@mistralai/mistralai").catch(() => null);
49
+ if (!MistralClient) throw new Error("SDK not installed");
50
+ const client = new MistralClient(this.apiKey);
51
+
52
+ // Build connectors from tools
53
+ const connectors = config.tools?.map((t) => ({
54
+ type: CONNECTOR_MAP[t.name] || "mcp",
55
+ })).filter(Boolean);
56
+
57
+ const messages: Array<{ role: string; content: string }> = [
58
+ ...(config.instruction ? [{ role: "system", content: config.instruction }] : []),
59
+ ...(config.history || []).map((m) => ({ role: m.role, content: m.content })),
60
+ { role: "user", content: prompt },
61
+ ];
62
+
63
+ const response = await client.chat({
64
+ model: config.model || "mistral-large-latest",
65
+ messages,
66
+ ...(connectors && connectors.length > 0 && { connectors }),
67
+ });
68
+
69
+ output = response.choices?.[0]?.message?.content || "";
70
+ history.push({ role: "assistant", content: output });
71
+
72
+ return {
73
+ output,
74
+ history,
75
+ toolCallCount,
76
+ usage: response.usage ? {
77
+ inputTokens: response.usage.prompt_tokens || 0,
78
+ outputTokens: response.usage.completion_tokens || 0,
79
+ totalTokens: response.usage.total_tokens || 0,
80
+ } : undefined,
81
+ };
82
+ } catch {
83
+ // Fall back to direct HTTP
84
+ return await this.runViaDirectHTTP(prompt, config, history);
85
+ }
86
+ }
87
+
88
+ private async runViaDirectHTTP(
89
+ prompt: string,
90
+ config: AgentConfig,
91
+ history: AgentMessage[],
92
+ ): Promise<AgentResult> {
93
+ const maxTurns = config.maxTurns || 10;
94
+ let toolCallCount = 0;
95
+ let totalInputTokens = 0;
96
+ let totalOutputTokens = 0;
97
+ let output = "";
98
+
99
+ const messages: Array<{ role: string; content: string }> = [
100
+ ...(config.instruction ? [{ role: "system", content: config.instruction }] : []),
101
+ ...(config.history || []).map((m) => ({ role: m.role, content: m.content })),
102
+ { role: "user", content: prompt },
103
+ ];
104
+
105
+ for (let turn = 0; turn < maxTurns; turn++) {
106
+ const body: Record<string, unknown> = {
107
+ model: config.model || "mistral-large-latest",
108
+ messages,
109
+ };
110
+
111
+ if (config.tools && config.tools.length > 0) {
112
+ body.tools = config.tools.map((t) => ({
113
+ type: CONNECTOR_MAP[t.name] || "function",
114
+ ...(CONNECTOR_MAP[t.name] ? {} : {
115
+ function: {
116
+ name: t.name,
117
+ description: t.description,
118
+ parameters: t.parameters,
119
+ },
120
+ }),
121
+ }));
122
+ }
123
+
124
+ const response = await fetch("https://api.mistral.ai/v1/chat/completions", {
125
+ method: "POST",
126
+ headers: {
127
+ "Content-Type": "application/json",
128
+ Authorization: `Bearer ${this.apiKey}`,
129
+ },
130
+ body: JSON.stringify(body),
131
+ });
132
+
133
+ if (!response.ok) {
134
+ const errorText = await response.text();
135
+ return {
136
+ output: "",
137
+ history,
138
+ toolCallCount,
139
+ error: `Mistral API error: ${response.status} ${errorText}`,
140
+ };
141
+ }
142
+
143
+ const data = await response.json();
144
+ const choice = data.choices?.[0];
145
+ if (!choice) break;
146
+
147
+ if (data.usage) {
148
+ totalInputTokens += data.usage.prompt_tokens || 0;
149
+ totalOutputTokens += data.usage.completion_tokens || 0;
150
+ }
151
+
152
+ const message = choice.message;
153
+ messages.push({ role: message.role, content: message.content || "" });
154
+ history.push({ role: message.role, content: message.content || "" });
155
+
156
+ if (message.tool_calls && message.tool_calls.length > 0) {
157
+ toolCallCount += message.tool_calls.length;
158
+ for (const toolCall of message.tool_calls) {
159
+ const args = JSON.parse(toolCall.function?.arguments || "{}");
160
+ const tool = config.tools?.find((t) => t.name === toolCall.function?.name);
161
+ let result = "Tool not found";
162
+ if (tool) {
163
+ try {
164
+ result = await tool.execute(args);
165
+ } catch (e) {
166
+ result = `Tool error: ${e instanceof Error ? e.message : String(e)}`;
167
+ }
168
+ }
169
+ messages.push({ role: "tool", content: result });
170
+ history.push({ role: "tool", content: result, toolCallId: toolCall.id, toolName: toolCall.function?.name });
171
+ }
172
+ } else {
173
+ output = message.content || "";
174
+ break;
175
+ }
176
+ }
177
+
178
+ return {
179
+ output,
180
+ history,
181
+ toolCallCount,
182
+ usage: {
183
+ inputTokens: totalInputTokens,
184
+ outputTokens: totalOutputTokens,
185
+ totalTokens: totalInputTokens + totalOutputTokens,
186
+ },
187
+ };
188
+ }
189
+ }
package/src/index.ts ADDED
@@ -0,0 +1,153 @@
1
+ /** Mistral provider extension for OMPv1. */
2
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
3
+ import {
4
+ BatchStore,
5
+ CredentialResolver,
6
+ CapabilityRegistry,
7
+ BatchEligibility,
8
+ OpenAICompatibleBatchClient,
9
+ } from "@omp-provider-capabilities/core";
10
+
11
+ export interface MistralAgentToolConfig {
12
+ codeExecution: boolean;
13
+ webSearch: boolean;
14
+ imageGen: boolean;
15
+ mcp: boolean;
16
+ }
17
+
18
+ export const DEFAULT_MISTRAL_CONFIG: MistralAgentToolConfig = {
19
+ codeExecution: false,
20
+ webSearch: false,
21
+ imageGen: false,
22
+ mcp: false,
23
+ };
24
+
25
+ export class MistralDirectHttpClient {
26
+ private apiKey: string;
27
+ private config: MistralAgentToolConfig;
28
+
29
+ constructor(apiKey: string, config: MistralAgentToolConfig) {
30
+ this.apiKey = apiKey;
31
+ this.config = config;
32
+ }
33
+
34
+ async sendMessage(messages: Array<{ role: string; content: string }>, model: string): Promise<unknown> {
35
+ const body: Record<string, unknown> = { model, messages };
36
+ const tools: Array<Record<string, unknown>> = [];
37
+ if (this.config.codeExecution) tools.push({ type: "code_execution" });
38
+ if (this.config.webSearch) tools.push({ type: "web_search" });
39
+ if (this.config.imageGen) tools.push({ type: "image_gen" });
40
+ if (this.config.mcp) tools.push({ type: "mcp" });
41
+ if (tools.length > 0) body.tools = tools;
42
+
43
+ const response = await fetch("https://api.mistral.ai/v1/chat/completions", {
44
+ method: "POST",
45
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}` },
46
+ body: JSON.stringify(body),
47
+ });
48
+ if (!response.ok) {
49
+ const errorText = await response.text();
50
+ throw new Error(`Mistral direct HTTP failed: ${response.status} ${errorText}`);
51
+ }
52
+ return response.json();
53
+ }
54
+ }
55
+
56
+ export default function mistralExtension(pi: ExtensionAPI) {
57
+ const store = new BatchStore();
58
+ const credentialResolver = new CredentialResolver();
59
+ const registry = new CapabilityRegistry();
60
+ const eligibility = new BatchEligibility(registry);
61
+
62
+ let batchClient: OpenAICompatibleBatchClient | null = null;
63
+ let directClient: MistralDirectHttpClient | null = null;
64
+ let agentConfig: MistralAgentToolConfig = DEFAULT_MISTRAL_CONFIG;
65
+
66
+ pi.on("session_start", async (_event, ctx) => {
67
+ pi.logger.debug("Mistral provider extension loaded");
68
+ const creds = await credentialResolver.resolveForProvider("mistral", ctx);
69
+ if (creds && credentialResolver.isBatchEligible(creds)) {
70
+ const apiKey = process.env.MISTRAL_API_KEY || "";
71
+ if (apiKey) {
72
+ batchClient = new OpenAICompatibleBatchClient(
73
+ { baseUrl: "https://api.mistral.ai", apiKey },
74
+ store,
75
+ "mistral",
76
+ );
77
+ directClient = new MistralDirectHttpClient(apiKey, agentConfig);
78
+ }
79
+ }
80
+ await store.restore();
81
+ });
82
+
83
+ pi.registerTool({
84
+ name: "mistral_batch_submit",
85
+ label: "Mistral Batch Submit",
86
+ description: "Submit a batch job to Mistral.",
87
+ parameters: pi.zod.object({
88
+ requests: pi.zod
89
+ .array(
90
+ pi.zod.object({
91
+ id: pi.zod.string().describe("Unique request ID"),
92
+ model: pi.zod.string().describe("Model name"),
93
+ messages: pi.zod
94
+ .array(
95
+ pi.zod.object({
96
+ role: pi.zod.enum(["system", "user", "assistant"]).describe("Message role"),
97
+ content: pi.zod.string().describe("Message content"),
98
+ }),
99
+ )
100
+ .describe("Messages"),
101
+ }),
102
+ )
103
+ .describe("Batch requests"),
104
+ }),
105
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
106
+ const p = params as { requests: Array<{ id: string; model: string; messages: Array<{ role: string; content: string }> }> };
107
+ if (!batchClient) {
108
+ return { content: [{ type: "text", text: "Mistral batch client not available." }], isError: true };
109
+ }
110
+ try {
111
+ const job = await batchClient.submit(p.requests);
112
+ return { content: [{ type: "text", text: `Batch submitted: ${job.id}` }], details: { job } };
113
+ } catch (error) {
114
+ const msg = error instanceof Error ? error.message : String(error);
115
+ return { content: [{ type: "text", text: `Batch submit failed: ${msg}` }], isError: true };
116
+ }
117
+ },
118
+ });
119
+
120
+ pi.registerTool({
121
+ name: "mistral_agent_call",
122
+ label: "Mistral Agent Call",
123
+ description: "Make a direct API call to Mistral with Agents API tools (code execution, web search).",
124
+ parameters: pi.zod.object({
125
+ model: pi.zod.string().describe("Model name"),
126
+ messages: pi.zod
127
+ .array(
128
+ pi.zod.object({
129
+ role: pi.zod.enum(["system", "user", "assistant"]).describe("Message role"),
130
+ content: pi.zod.string().describe("Message content"),
131
+ }),
132
+ )
133
+ .describe("Messages"),
134
+ }),
135
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
136
+ const p = params as { model: string; messages: Array<{ role: string; content: string }> };
137
+ if (!directClient) {
138
+ return { content: [{ type: "text", text: "Mistral direct HTTP client not available." }], isError: true };
139
+ }
140
+ try {
141
+ const result = await directClient.sendMessage(p.messages, p.model);
142
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], details: { result } };
143
+ } catch (error) {
144
+ const msg = error instanceof Error ? error.message : String(error);
145
+ return { content: [{ type: "text", text: `Mistral agent call failed: ${msg}` }], isError: true };
146
+ }
147
+ },
148
+ });
149
+
150
+ pi.on("session_shutdown", async () => {
151
+ await store.save();
152
+ });
153
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.