@omp-provider-capabilities/xai 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/xai",
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": "xAI provider extension: batch execution, agentic tools (web browse, X search, code execution).",
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,176 @@
1
+ /**
2
+ * xAI Agent SDK wrapper.
3
+ *
4
+ * Wraps @xai-official/sdk (experimental, pre-1.0) for Grok.
5
+ * Provides responses API with server-hosted tools (web search, X search,
6
+ * code execution, document retrieval).
7
+ */
8
+
9
+ import type {
10
+ AgentSDK,
11
+ AgentConfig,
12
+ AgentResult,
13
+ AgentMessage,
14
+ } from "@omp-provider-capabilities/core";
15
+
16
+ /**
17
+ * xAI Agent SDK implementation.
18
+ *
19
+ * Uses @xai-official/sdk's responses.create() for agent loops with server tools.
20
+ */
21
+ export class xAIAgentSDK implements AgentSDK {
22
+ public provider = "xai";
23
+ private apiKey: string;
24
+
25
+ constructor(apiKey: string) {
26
+ this.apiKey = apiKey;
27
+ }
28
+
29
+ isAvailable(): boolean {
30
+ return !!this.apiKey;
31
+ }
32
+
33
+ async run(prompt: string, config: AgentConfig): Promise<AgentResult> {
34
+ const history: AgentMessage[] = [...(config.history || [])];
35
+ let toolCallCount = 0;
36
+ let output = "";
37
+
38
+ try {
39
+ // Try the xAI SDK first
40
+ // @ts-ignore - optional peer dependency
41
+ const { default: xai } = await import("@xai-official/sdk").catch(() => null);
42
+ if (!xai) throw new Error("SDK not installed");
43
+ const client = new xai({ apiKey: this.apiKey });
44
+
45
+ const input = config.history
46
+ ? [...config.history.map((m) => ({ role: m.role, content: m.content })), { role: "user", content: prompt }]
47
+ : prompt;
48
+
49
+ const response = await client.responses.create({
50
+ model: config.model || "grok-4",
51
+ input,
52
+ stream: false,
53
+ ...(config.tools && config.tools.length > 0 && {
54
+ tools: config.tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters } })),
55
+ }),
56
+ });
57
+
58
+ output = response.output?.[0]?.content?.[0]?.text || "";
59
+ history.push({ role: "assistant", content: output });
60
+
61
+ return {
62
+ output,
63
+ history,
64
+ toolCallCount,
65
+ usage: response.usage ? {
66
+ inputTokens: response.usage.input_tokens || 0,
67
+ outputTokens: response.usage.output_tokens || 0,
68
+ totalTokens: response.usage.total_tokens || 0,
69
+ } : undefined,
70
+ };
71
+ } catch {
72
+ // Fall back to direct HTTP
73
+ return await this.runViaDirectHTTP(prompt, config, history);
74
+ }
75
+ }
76
+
77
+ private async runViaDirectHTTP(
78
+ prompt: string,
79
+ config: AgentConfig,
80
+ history: AgentMessage[],
81
+ ): Promise<AgentResult> {
82
+ const maxTurns = config.maxTurns || 10;
83
+ let toolCallCount = 0;
84
+ let totalInputTokens = 0;
85
+ let totalOutputTokens = 0;
86
+ let output = "";
87
+
88
+ const messages: Array<{ role: string; content: string }> = [
89
+ ...(config.instruction ? [{ role: "system", content: config.instruction }] : []),
90
+ ...(config.history || []).map((m) => ({ role: m.role, content: m.content })),
91
+ { role: "user", content: prompt },
92
+ ];
93
+
94
+ for (let turn = 0; turn < maxTurns; turn++) {
95
+ const body: Record<string, unknown> = {
96
+ model: config.model || "grok-4",
97
+ messages,
98
+ };
99
+
100
+ if (config.tools && config.tools.length > 0) {
101
+ body.tools = config.tools.map((t) => ({
102
+ type: "function",
103
+ function: {
104
+ name: t.name,
105
+ description: t.description,
106
+ parameters: t.parameters,
107
+ },
108
+ }));
109
+ }
110
+
111
+ const response = await fetch("https://api.x.ai/v1/chat/completions", {
112
+ method: "POST",
113
+ headers: {
114
+ "Content-Type": "application/json",
115
+ Authorization: `Bearer ${this.apiKey}`,
116
+ },
117
+ body: JSON.stringify(body),
118
+ });
119
+
120
+ if (!response.ok) {
121
+ const errorText = await response.text();
122
+ return {
123
+ output: "",
124
+ history,
125
+ toolCallCount,
126
+ error: `xAI API error: ${response.status} ${errorText}`,
127
+ };
128
+ }
129
+
130
+ const data = await response.json();
131
+ const choice = data.choices?.[0];
132
+ if (!choice) break;
133
+
134
+ if (data.usage) {
135
+ totalInputTokens += data.usage.prompt_tokens || 0;
136
+ totalOutputTokens += data.usage.completion_tokens || 0;
137
+ }
138
+
139
+ const message = choice.message;
140
+ messages.push({ role: message.role, content: message.content || "" });
141
+ history.push({ role: message.role, content: message.content || "" });
142
+
143
+ if (message.tool_calls && message.tool_calls.length > 0) {
144
+ toolCallCount += message.tool_calls.length;
145
+ for (const toolCall of message.tool_calls) {
146
+ const args = JSON.parse(toolCall.function?.arguments || "{}");
147
+ const tool = config.tools?.find((t) => t.name === toolCall.function?.name);
148
+ let result = "Tool not found";
149
+ if (tool) {
150
+ try {
151
+ result = await tool.execute(args);
152
+ } catch (e) {
153
+ result = `Tool error: ${e instanceof Error ? e.message : String(e)}`;
154
+ }
155
+ }
156
+ messages.push({ role: "tool", content: result });
157
+ history.push({ role: "tool", content: result, toolCallId: toolCall.id, toolName: toolCall.function?.name });
158
+ }
159
+ } else {
160
+ output = message.content || "";
161
+ break;
162
+ }
163
+ }
164
+
165
+ return {
166
+ output,
167
+ history,
168
+ toolCallCount,
169
+ usage: {
170
+ inputTokens: totalInputTokens,
171
+ outputTokens: totalOutputTokens,
172
+ totalTokens: totalInputTokens + totalOutputTokens,
173
+ },
174
+ };
175
+ }
176
+ }
package/src/index.ts ADDED
@@ -0,0 +1,153 @@
1
+ /** xAI 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 xAIAgenticToolConfig {
12
+ webBrowse: boolean;
13
+ xSearch: boolean;
14
+ codeExecution: boolean;
15
+ documentRetrieval: boolean;
16
+ }
17
+
18
+ export const DEFAULT_XAI_CONFIG: xAIAgenticToolConfig = {
19
+ webBrowse: false,
20
+ xSearch: false,
21
+ codeExecution: false,
22
+ documentRetrieval: false,
23
+ };
24
+
25
+ export class xAIDirectHttpClient {
26
+ private apiKey: string;
27
+ private config: xAIAgenticToolConfig;
28
+
29
+ constructor(apiKey: string, config: xAIAgenticToolConfig) {
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.webBrowse) tools.push({ type: "function", function: { name: "web_browse" } });
38
+ if (this.config.xSearch) tools.push({ type: "function", function: { name: "x_search" } });
39
+ if (this.config.codeExecution) tools.push({ type: "function", function: { name: "code_execution" } });
40
+ if (this.config.documentRetrieval) tools.push({ type: "function", function: { name: "document_retrieval" } });
41
+ if (tools.length > 0) body.tools = tools;
42
+
43
+ const response = await fetch("https://api.x.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(`xAI direct HTTP failed: ${response.status} ${errorText}`);
51
+ }
52
+ return response.json();
53
+ }
54
+ }
55
+
56
+ export default function xaiExtension(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: xAIDirectHttpClient | null = null;
64
+ let agenticConfig: xAIAgenticToolConfig = DEFAULT_XAI_CONFIG;
65
+
66
+ pi.on("session_start", async (_event, ctx) => {
67
+ pi.logger.debug("xAI provider extension loaded");
68
+ const creds = await credentialResolver.resolveForProvider("xai", ctx);
69
+ if (creds && credentialResolver.isBatchEligible(creds)) {
70
+ const apiKey = process.env.XAI_API_KEY || "";
71
+ if (apiKey) {
72
+ batchClient = new OpenAICompatibleBatchClient(
73
+ { baseUrl: "https://api.x.ai", apiKey },
74
+ store,
75
+ "xai",
76
+ );
77
+ directClient = new xAIDirectHttpClient(apiKey, agenticConfig);
78
+ }
79
+ }
80
+ await store.restore();
81
+ });
82
+
83
+ pi.registerTool({
84
+ name: "xai_batch_submit",
85
+ label: "xAI Batch Submit",
86
+ description: "Submit a batch job to xAI.",
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: "xAI 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: "xai_agentic_call",
122
+ label: "xAI Agentic Call",
123
+ description: "Make a direct API call to xAI with agentic tools (web browse, X search, code execution).",
124
+ parameters: pi.zod.object({
125
+ model: pi.zod.string().describe("Model (e.g., grok-4.1-fast)"),
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: "xAI 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: `xAI agentic 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.