-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathclient.ts
More file actions
259 lines (238 loc) · 8.43 KB
/
client.ts
File metadata and controls
259 lines (238 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import z from "zod"
import path from "path"
import { Global } from "../../global"
import { Filesystem } from "../../util/filesystem"
const DEFAULT_MCP_URL = "https://mcpserver.getaltimate.com/sse"
const AltimateCredentials = z.object({
altimateUrl: z.string(),
altimateInstanceName: z.string(),
altimateApiKey: z.string(),
mcpServerUrl: z.string().optional(),
})
type AltimateCredentials = z.infer<typeof AltimateCredentials>
const DatamateSummary = z.object({
id: z.coerce.string(),
name: z.string(),
description: z.string().nullable().optional(),
integrations: z
.array(
z.object({
id: z.coerce.string(),
tools: z.array(z.object({ key: z.string() })).optional(),
}),
)
.nullable()
.optional(),
memory_enabled: z.boolean().optional(),
privacy: z.string().optional(),
})
const IntegrationSummary = z.object({
id: z.coerce.string(),
name: z.string().optional(),
description: z.string().nullable().optional(),
tools: z
.array(
z.object({
key: z.string(),
name: z.string().optional(),
enable_all: z.array(z.string()).optional(),
}),
)
.optional(),
})
export namespace AltimateApi {
export function credentialsPath(): string {
return path.join(Global.Path.home, ".altimate", "altimate.json")
}
export async function isConfigured(): Promise<boolean> {
return Filesystem.exists(credentialsPath())
}
function resolveEnvVars(obj: unknown): unknown {
if (typeof obj === "string") {
return obj.replace(/\$\{env:([^}]+)\}/g, (_, envVar) => {
const value = process.env[envVar]
if (!value) throw new Error(`Environment variable ${envVar} not found`)
return value
})
}
if (Array.isArray(obj)) return obj.map(resolveEnvVars)
if (obj && typeof obj === "object")
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, resolveEnvVars(v)]))
return obj
}
export async function getCredentials(): Promise<AltimateCredentials> {
const p = credentialsPath()
if (!(await Filesystem.exists(p))) {
throw new Error(`Altimate credentials not found at ${p}`)
}
const raw = resolveEnvVars(JSON.parse(await Filesystem.readText(p)))
return AltimateCredentials.parse(raw)
}
export function parseAltimateKey(value: string): {
altimateUrl: string
altimateInstanceName: string
altimateApiKey: string
} | null {
const parts = value.trim().split("::")
if (parts.length < 3) return null
const url = parts[0].trim()
const instance = parts[1].trim()
const key = parts.slice(2).join("::").trim()
if (!url || !instance || !key) return null
if (!url.startsWith("http://") && !url.startsWith("https://")) return null
return { altimateUrl: url, altimateInstanceName: instance, altimateApiKey: key }
}
export async function saveCredentials(creds: {
altimateUrl: string
altimateInstanceName: string
altimateApiKey: string
mcpServerUrl?: string
}): Promise<void> {
await Filesystem.writeJson(credentialsPath(), creds, 0o600)
}
const VALID_TENANT_REGEX = /^[a-z_][a-z0-9_-]*$/
/** Validates credentials against the Altimate API.
* Mirrors AltimateSettingsHelper.validateSettings from altimate-mcp-engine. */
export async function validateCredentials(creds: {
altimateUrl: string
altimateInstanceName: string
altimateApiKey: string
}): Promise<{ ok: true } | { ok: false; error: string }> {
if (!VALID_TENANT_REGEX.test(creds.altimateInstanceName)) {
return {
ok: false,
error:
"Invalid instance name (must be lowercase letters, numbers, underscores, hyphens, starting with letter or underscore)",
}
}
try {
const url = `${creds.altimateUrl.replace(/\/+$/, "")}/dbt/v3/validate-credentials`
const res = await fetch(url, {
method: "GET",
headers: {
"x-tenant": creds.altimateInstanceName,
Authorization: `Bearer ${creds.altimateApiKey}`,
"Content-Type": "application/json",
},
})
if (res.status === 401) {
const body = await res.text()
return { ok: false, error: `Invalid API key - ${body}` }
}
if (res.status === 403) {
const body = await res.text()
return { ok: false, error: `Invalid instance name - ${body}` }
}
if (!res.ok) {
return { ok: false, error: `Connection failed (${res.status} ${res.statusText})` }
}
return { ok: true }
} catch {
return { ok: false, error: "Could not reach Altimate API" }
}
}
async function request(creds: AltimateCredentials, method: string, endpoint: string, body?: unknown) {
const url = `${creds.altimateUrl}${endpoint}`
const res = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${creds.altimateApiKey}`,
"x-tenant": creds.altimateInstanceName,
},
...(body ? { body: JSON.stringify(body) } : {}),
})
if (!res.ok) {
throw new Error(`API ${method} ${endpoint} failed with status ${res.status}`)
}
return res.json()
}
export async function listDatamates() {
const creds = await getCredentials()
const data = await request(creds, "GET", "/datamates/")
const list = Array.isArray(data) ? data : (data.datamates ?? data.data ?? [])
return list.map((d: unknown) => DatamateSummary.parse(d)) as z.infer<typeof DatamateSummary>[]
}
export async function getDatamate(id: string) {
const creds = await getCredentials()
try {
const data = await request(creds, "GET", `/datamates/${id}/summary`)
const raw = data.datamate ?? data
return DatamateSummary.parse(raw)
} catch (e) {
// Fallback to list if single-item endpoint is unavailable (404)
if (e instanceof Error && e.message.includes("status 404")) {
const all = await listDatamates()
const found = all.find((d) => d.id === id)
if (!found) {
throw new Error(`Datamate with ID ${id} not found`)
}
return found
}
throw e
}
}
export async function createDatamate(payload: {
name: string
description?: string
integrations?: Array<{ id: string; tools: Array<{ key: string }> }>
memory_enabled?: boolean
privacy?: string
}) {
const creds = await getCredentials()
const data = await request(creds, "POST", "/datamates/", payload)
// Backend returns { id: number } for create
const id = String(data.id ?? data.datamate?.id)
return { id, name: payload.name }
}
export async function updateDatamate(
id: string,
payload: {
name?: string
description?: string
integrations?: Array<{ id: string; tools: Array<{ key: string }> }>
memory_enabled?: boolean
privacy?: string
},
) {
const creds = await getCredentials()
const data = await request(creds, "PATCH", `/datamates/${id}`, payload)
const raw = data.datamate ?? data
return DatamateSummary.parse(raw)
}
export async function deleteDatamate(id: string) {
const creds = await getCredentials()
await request(creds, "DELETE", `/datamates/${id}`)
}
export async function listIntegrations() {
const creds = await getCredentials()
const data = await request(creds, "GET", "/datamate_integrations/")
const list = Array.isArray(data) ? data : (data.integrations ?? data.data ?? [])
return list.map((d: unknown) => IntegrationSummary.parse(d)) as z.infer<typeof IntegrationSummary>[]
}
/** Resolve integration IDs to full integration objects with all tools enabled (matching frontend behavior). */
export async function resolveIntegrations(
integrationIds: string[],
): Promise<Array<{ id: string; tools: Array<{ key: string }> }>> {
const allIntegrations = await listIntegrations()
return integrationIds.map((id) => {
const def = allIntegrations.find((i) => i.id === id)
const tools =
def?.tools?.flatMap((t) => (t.enable_all ?? [t.key]).map((k) => ({ key: k }))) ?? []
return { id, tools }
})
}
export function buildMcpConfig(creds: AltimateCredentials, datamateId: string) {
return {
type: "remote" as const,
url: creds.mcpServerUrl ?? DEFAULT_MCP_URL,
oauth: false as const,
headers: {
Authorization: `Bearer ${creds.altimateApiKey}`,
"x-datamate-id": String(datamateId),
"x-tenant": creds.altimateInstanceName,
"x-altimate-url": creds.altimateUrl,
},
}
}
}