@evalops/maestro 0.10.10 → 0.10.11

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.
@@ -0,0 +1,73 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
+ import { getOAuthToken, hasOAuthCredentials, login } from "../oauth/index.js";
3
+ import { loadOAuthCredentials, saveOAuthCredentials } from "../oauth/storage.js";
4
+ export interface EvalOpsInitOptions {
5
+ agentType?: string;
6
+ apiKeyScopes?: string[];
7
+ expiresInDays?: number;
8
+ forceLogin?: boolean;
9
+ json?: boolean;
10
+ keyName?: string;
11
+ manifestUrl?: string;
12
+ mcpUrl?: string;
13
+ registerScopes?: string[];
14
+ rotateKey?: boolean;
15
+ surface?: string;
16
+ ttlSeconds?: number;
17
+ workspaceId?: string;
18
+ }
19
+ export interface EvalOpsAgentMcpMetadata {
20
+ agentId?: string;
21
+ apiKey?: string;
22
+ createdAt: string;
23
+ endpoint: string;
24
+ expiresAt?: string;
25
+ keyId?: string;
26
+ keyName?: string;
27
+ keyPrefix?: string;
28
+ manifestUrl?: string;
29
+ registeredAt: string;
30
+ registryVisible?: boolean;
31
+ runId?: string;
32
+ scopes?: string[];
33
+ sessionExpiresAt?: string;
34
+ surface: string;
35
+ type: "agent-mcp";
36
+ workspaceId?: string;
37
+ }
38
+ export interface EvalOpsInitResult {
39
+ agentId?: string;
40
+ apiKeyCreated: boolean;
41
+ endpoint: string;
42
+ keyPrefix?: string;
43
+ manifestUrl?: string;
44
+ organizationId?: string;
45
+ registryVisible?: boolean;
46
+ runId?: string;
47
+ scopesGranted?: string[];
48
+ sessionExpiresAt?: string;
49
+ stored: boolean;
50
+ }
51
+ export interface EvalOpsInitStatus {
52
+ message: string;
53
+ }
54
+ export interface EvalOpsInitDependencies {
55
+ createMcpClient?: (endpoint: string, bearerToken: string) => EvalOpsMcpClient;
56
+ fetch?: typeof fetch;
57
+ getOAuthToken?: typeof getOAuthToken;
58
+ hasOAuthCredentials?: typeof hasOAuthCredentials;
59
+ loadCredentials?: typeof loadOAuthCredentials;
60
+ login?: typeof login;
61
+ now?: () => Date;
62
+ onAuthUrl?: (url: string) => void;
63
+ onStatus?: (status: EvalOpsInitStatus) => void;
64
+ saveCredentials?: typeof saveOAuthCredentials;
65
+ }
66
+ export interface EvalOpsMcpClient {
67
+ callTool(name: string, args: Record<string, unknown>): Promise<CallToolResult>;
68
+ close(): Promise<void>;
69
+ connect(): Promise<void>;
70
+ }
71
+ export declare function getStoredEvalOpsAgentMcpMetadata(): EvalOpsAgentMcpMetadata | undefined;
72
+ export declare function bootstrapEvalOpsAgent(options?: EvalOpsInitOptions, dependencies?: EvalOpsInitDependencies): Promise<EvalOpsInitResult>;
73
+ //# sourceMappingURL=agent-bootstrap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-bootstrap.d.ts","sourceRoot":"","sources":["../../src/evalops/agent-bootstrap.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAEN,oBAAoB,EACpB,oBAAoB,EACpB,MAAM,qBAAqB,CAAC;AAkB7B,MAAM,WAAW,kBAAkB;IAClC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,CAAC,EAAE,MA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CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,gBAAgB,CAAC;IAC9E,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,aAAa,CAAC,EAAE,OAAO,aAAa,CAAC;IACrC,mBAAmB,CAAC,EAAE,OAAO,mBAAmB,CAAC;IACjD,eAAe,CAAC,EAAE,OAAO,oBAAoB,CAAC;IAC9C,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,KAAK,IAAI,CAAC;IAC/C,eAAe,CAAC,EAAE,OAAO,oBAAoB,CAAC;CAC9C;AAED,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CACP,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC3B,OAAO,CAAC,cAAc,CAAC,CAAC;IAC3B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAyFD,wBAAgB,gCAAgC,IAC7C,uBAAuB,GACvB,SAAS,CAEX;AAkTD,wBAAsB,qBAAqB,CAC1C,OAAO,GAAE,kBAAuB,EAChC,YAAY,GAAE,uBAA4B,GACxC,OAAO,CAAC,iBAAiB,CAAC,CAyH5B"}
@@ -0,0 +1,380 @@
1
+ import { hostname } from "node:os";
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
4
+ import { getOAuthToken, hasOAuthCredentials, login } from "../oauth/index.js";
5
+ import { loadOAuthCredentials, saveOAuthCredentials, } from "../oauth/storage.js";
6
+ import { getPackageVersion } from "../package-metadata.js";
7
+ import { getEnvValue, normalizeBaseUrl } from "../platform/client.js";
8
+ const DEFAULT_AGENT_MCP_BASE_URL = "https://app.evalops.dev";
9
+ const AGENT_MCP_MANIFEST_PATH = "/.well-known/evalops/agent-mcp.json";
10
+ const AGENT_MCP_PATH = "/mcp";
11
+ const DEFAULT_AGENT_TYPE = "maestro";
12
+ const DEFAULT_SURFACE = "cli";
13
+ const DEFAULT_REGISTER_SCOPES = ["llm_gateway:invoke"];
14
+ const DEFAULT_API_KEY_SCOPES = [
15
+ "agent:register",
16
+ "agent:heartbeat",
17
+ "governance:evaluate",
18
+ "memories:read",
19
+ "meter:record",
20
+ ];
21
+ function isRecord(value) {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+ function nonEmptyString(value) {
25
+ return typeof value === "string" && value.trim().length > 0
26
+ ? value.trim()
27
+ : undefined;
28
+ }
29
+ function stringArray(value) {
30
+ if (!Array.isArray(value)) {
31
+ return undefined;
32
+ }
33
+ const values = value
34
+ .map((entry) => nonEmptyString(entry))
35
+ .filter((entry) => Boolean(entry));
36
+ return values.length > 0 ? values : undefined;
37
+ }
38
+ function positiveInteger(value) {
39
+ return typeof value === "number" && Number.isInteger(value) && value > 0
40
+ ? value
41
+ : undefined;
42
+ }
43
+ function getStoredAgentMcpMetadata(credentials) {
44
+ const metadata = credentials?.metadata;
45
+ const agentMcp = isRecord(metadata?.agentMcp) ? metadata.agentMcp : undefined;
46
+ const apiKey = nonEmptyString(agentMcp?.apiKey);
47
+ const endpoint = nonEmptyString(agentMcp?.endpoint);
48
+ const registeredAt = nonEmptyString(agentMcp?.registeredAt);
49
+ const createdAt = nonEmptyString(agentMcp?.createdAt);
50
+ const surface = nonEmptyString(agentMcp?.surface);
51
+ if (!apiKey || !endpoint || !registeredAt || !createdAt || !surface) {
52
+ return undefined;
53
+ }
54
+ return {
55
+ type: "agent-mcp",
56
+ apiKey,
57
+ createdAt,
58
+ endpoint,
59
+ registeredAt,
60
+ surface,
61
+ agentId: nonEmptyString(agentMcp?.agentId),
62
+ expiresAt: nonEmptyString(agentMcp?.expiresAt),
63
+ keyId: nonEmptyString(agentMcp?.keyId),
64
+ keyName: nonEmptyString(agentMcp?.keyName),
65
+ keyPrefix: nonEmptyString(agentMcp?.keyPrefix),
66
+ manifestUrl: nonEmptyString(agentMcp?.manifestUrl),
67
+ registryVisible: typeof agentMcp?.registryVisible === "boolean"
68
+ ? agentMcp.registryVisible
69
+ : undefined,
70
+ runId: nonEmptyString(agentMcp?.runId),
71
+ scopes: stringArray(agentMcp?.scopes),
72
+ sessionExpiresAt: nonEmptyString(agentMcp?.sessionExpiresAt),
73
+ workspaceId: nonEmptyString(agentMcp?.workspaceId),
74
+ };
75
+ }
76
+ export function getStoredEvalOpsAgentMcpMetadata() {
77
+ return getStoredAgentMcpMetadata(loadOAuthCredentials("evalops"));
78
+ }
79
+ function normalizeMcpEndpoint(url) {
80
+ const normalized = normalizeBaseUrl(url);
81
+ const parsed = new URL(normalized);
82
+ if (parsed.pathname === "" ||
83
+ parsed.pathname === "/" ||
84
+ parsed.pathname === AGENT_MCP_MANIFEST_PATH) {
85
+ parsed.pathname = AGENT_MCP_PATH;
86
+ parsed.search = "";
87
+ parsed.hash = "";
88
+ }
89
+ return normalizeBaseUrl(parsed.toString());
90
+ }
91
+ function normalizeManifestUrl(url) {
92
+ const normalized = normalizeBaseUrl(url);
93
+ const parsed = new URL(normalized);
94
+ if (parsed.pathname === "" || parsed.pathname === "/") {
95
+ parsed.pathname = AGENT_MCP_MANIFEST_PATH;
96
+ }
97
+ return parsed.toString();
98
+ }
99
+ async function resolveEndpointFromManifest(manifestUrl, fetchImpl) {
100
+ const response = await fetchImpl(manifestUrl, {
101
+ headers: { accept: "application/json" },
102
+ });
103
+ if (!response.ok) {
104
+ throw new Error(`Failed to fetch EvalOps MCP manifest (${response.status} ${response.statusText})`);
105
+ }
106
+ const payload = (await response.json());
107
+ const protocol = isRecord(payload) && isRecord(payload.protocol)
108
+ ? payload.protocol
109
+ : undefined;
110
+ const endpoint = nonEmptyString(protocol?.endpoint);
111
+ if (!endpoint) {
112
+ throw new Error("EvalOps MCP manifest did not include protocol.endpoint");
113
+ }
114
+ return { endpoint: normalizeMcpEndpoint(endpoint), manifestUrl };
115
+ }
116
+ async function resolveAgentMcpEndpoint(options, deps) {
117
+ if (options.mcpUrl) {
118
+ return { endpoint: normalizeMcpEndpoint(options.mcpUrl) };
119
+ }
120
+ if (options.manifestUrl) {
121
+ return resolveEndpointFromManifest(normalizeManifestUrl(options.manifestUrl), deps.fetch);
122
+ }
123
+ const configuredMcpUrl = getEnvValue([
124
+ "MAESTRO_PLATFORM_MCP_URL",
125
+ "MAESTRO_AGENT_MCP_URL",
126
+ "MAESTRO_EVALOPS_AGENT_MCP_URL",
127
+ ]);
128
+ if (configuredMcpUrl) {
129
+ return { endpoint: normalizeMcpEndpoint(configuredMcpUrl) };
130
+ }
131
+ const configuredManifestUrl = getEnvValue([
132
+ "MAESTRO_PLATFORM_MCP_MANIFEST_URL",
133
+ "MAESTRO_AGENT_MCP_MANIFEST_URL",
134
+ "MAESTRO_EVALOPS_AGENT_MCP_MANIFEST_URL",
135
+ ]);
136
+ if (configuredManifestUrl) {
137
+ return resolveEndpointFromManifest(normalizeManifestUrl(configuredManifestUrl), deps.fetch);
138
+ }
139
+ const stored = getStoredAgentMcpMetadata(deps.loadCredentials("evalops"));
140
+ if (stored?.endpoint) {
141
+ return {
142
+ endpoint: normalizeMcpEndpoint(stored.endpoint),
143
+ manifestUrl: stored.manifestUrl,
144
+ };
145
+ }
146
+ return resolveEndpointFromManifest(`${DEFAULT_AGENT_MCP_BASE_URL}${AGENT_MCP_MANIFEST_PATH}`, deps.fetch);
147
+ }
148
+ function createDefaultMcpClient(endpoint, bearerToken) {
149
+ const client = new Client({
150
+ name: "maestro",
151
+ version: getPackageVersion(),
152
+ }, {
153
+ capabilities: {},
154
+ });
155
+ const headers = {
156
+ accept: "application/json, text/event-stream",
157
+ "content-type": "application/json",
158
+ ...(bearerToken ? { authorization: `Bearer ${bearerToken}` } : {}),
159
+ };
160
+ const transport = new StreamableHTTPClientTransport(new URL(endpoint), {
161
+ requestInit: {
162
+ headers,
163
+ },
164
+ });
165
+ return {
166
+ callTool: (name, args) => client.callTool({
167
+ name,
168
+ arguments: args,
169
+ }),
170
+ close: () => client.close(),
171
+ connect: () => client.connect(transport),
172
+ };
173
+ }
174
+ async function callMcpTool(createClient, endpoint, token, toolName, args) {
175
+ const client = createClient(endpoint, token);
176
+ await client.connect();
177
+ try {
178
+ const result = await client.callTool(toolName, args);
179
+ if (result.isError) {
180
+ throw new Error(`${toolName} returned an MCP error`);
181
+ }
182
+ return parseToolOutput(toolName, result);
183
+ }
184
+ finally {
185
+ await client.close().catch(() => undefined);
186
+ }
187
+ }
188
+ function parseToolOutput(toolName, result) {
189
+ const structuredContent = isRecord(result.structuredContent)
190
+ ? result.structuredContent
191
+ : undefined;
192
+ if (structuredContent) {
193
+ return structuredContent;
194
+ }
195
+ const text = Array.isArray(result.content)
196
+ ? result.content
197
+ .map((entry) => entry.type === "text" && typeof entry.text === "string"
198
+ ? entry.text
199
+ : undefined)
200
+ .find((entry) => Boolean(entry))
201
+ : undefined;
202
+ if (text) {
203
+ const parsed = JSON.parse(text);
204
+ if (isRecord(parsed)) {
205
+ return parsed;
206
+ }
207
+ }
208
+ throw new Error(`${toolName} did not return structured JSON output`);
209
+ }
210
+ async function ensureEvalOpsLogin(options, deps) {
211
+ if (options.forceLogin || !deps.hasOAuthCredentials("evalops")) {
212
+ deps.onStatus({ message: "Opening EvalOps login" });
213
+ await deps.login("evalops", {
214
+ onAuthUrl: deps.onAuthUrl,
215
+ onStatus: (message) => deps.onStatus({ message }),
216
+ });
217
+ }
218
+ let token = await deps.getOAuthToken("evalops");
219
+ if (!token) {
220
+ deps.onStatus({ message: "Refreshing EvalOps login" });
221
+ await deps.login("evalops", {
222
+ onAuthUrl: deps.onAuthUrl,
223
+ onStatus: (message) => deps.onStatus({ message }),
224
+ });
225
+ token = await deps.getOAuthToken("evalops");
226
+ }
227
+ if (!token) {
228
+ throw new Error("EvalOps login did not produce an access token");
229
+ }
230
+ return token;
231
+ }
232
+ function buildKeyName(options, now) {
233
+ if (options.keyName?.trim()) {
234
+ return options.keyName.trim();
235
+ }
236
+ const host = hostname()
237
+ .replace(/[^a-zA-Z0-9._-]+/gu, "-")
238
+ .slice(0, 48);
239
+ return `maestro-init-${host || "local"}-${now.toISOString().slice(0, 10)}`;
240
+ }
241
+ async function createAgentAPIKey(options, endpoint, oauthToken, createClient, now) {
242
+ const output = await callMcpTool(createClient, endpoint, "", "evalops_create_api_key", {
243
+ name: buildKeyName(options, now),
244
+ scopes: options.apiKeyScopes ?? DEFAULT_API_KEY_SCOPES,
245
+ user_token: oauthToken,
246
+ ...(positiveInteger(options.expiresInDays)
247
+ ? { expires_in_days: options.expiresInDays }
248
+ : {}),
249
+ });
250
+ if (!nonEmptyString(output.api_key)) {
251
+ throw new Error("EvalOps API key creation did not return api_key");
252
+ }
253
+ return output;
254
+ }
255
+ async function registerAgent(options, endpoint, apiKey, createClient) {
256
+ const output = await callMcpTool(createClient, endpoint, "", "evalops_register", {
257
+ agent_type: options.agentType ?? DEFAULT_AGENT_TYPE,
258
+ capabilities: ["maestro:init", "maestro:cli"],
259
+ scopes: options.registerScopes ?? DEFAULT_REGISTER_SCOPES,
260
+ surface: options.surface ?? DEFAULT_SURFACE,
261
+ user_token: apiKey,
262
+ ...(positiveInteger(options.ttlSeconds)
263
+ ? { ttl_seconds: options.ttlSeconds }
264
+ : {}),
265
+ ...(options.workspaceId ? { workspace_id: options.workspaceId } : {}),
266
+ });
267
+ if (output.registered !== true || !nonEmptyString(output.agent_id)) {
268
+ throw new Error("EvalOps agent registration did not return an agent_id");
269
+ }
270
+ return output;
271
+ }
272
+ function organizationIdFromCredentials(credentials) {
273
+ return (nonEmptyString(credentials?.metadata?.organizationId) ??
274
+ nonEmptyString(credentials?.metadata?.organization_id));
275
+ }
276
+ function saveBootstrapMetadata(credentials, agentMcp, saveCredentials) {
277
+ saveCredentials("evalops", {
278
+ ...credentials,
279
+ metadata: {
280
+ ...credentials.metadata,
281
+ agentId: agentMcp.agentId ?? credentials.metadata?.agentId,
282
+ runId: agentMcp.runId ?? credentials.metadata?.runId,
283
+ surface: agentMcp.surface,
284
+ agentMcp,
285
+ },
286
+ });
287
+ }
288
+ export async function bootstrapEvalOpsAgent(options = {}, dependencies = {}) {
289
+ const deps = {
290
+ createMcpClient: dependencies.createMcpClient ?? createDefaultMcpClient,
291
+ fetch: dependencies.fetch ?? fetch,
292
+ getOAuthToken: dependencies.getOAuthToken ?? getOAuthToken,
293
+ hasOAuthCredentials: dependencies.hasOAuthCredentials ?? hasOAuthCredentials,
294
+ loadCredentials: dependencies.loadCredentials ?? loadOAuthCredentials,
295
+ login: dependencies.login ?? login,
296
+ now: dependencies.now ?? (() => new Date()),
297
+ onAuthUrl: dependencies.onAuthUrl ??
298
+ ((url) => {
299
+ process.stdout.write(`${url}\n`);
300
+ }),
301
+ onStatus: dependencies.onStatus ?? (() => undefined),
302
+ saveCredentials: dependencies.saveCredentials ?? saveOAuthCredentials,
303
+ };
304
+ const oauthToken = await ensureEvalOpsLogin(options, deps);
305
+ const endpoint = await resolveAgentMcpEndpoint(options, deps);
306
+ const credentialsBeforeKey = deps.loadCredentials("evalops");
307
+ const stored = getStoredAgentMcpMetadata(credentialsBeforeKey);
308
+ const now = deps.now();
309
+ let apiKey = stored && !options.rotateKey ? stored.apiKey : undefined;
310
+ let keyOutput;
311
+ let apiKeyCreated = false;
312
+ if (!apiKey) {
313
+ deps.onStatus({ message: "Creating EvalOps agent API key" });
314
+ keyOutput = await createAgentAPIKey(options, endpoint.endpoint, oauthToken, deps.createMcpClient, now);
315
+ apiKey = keyOutput.api_key;
316
+ apiKeyCreated = true;
317
+ }
318
+ else {
319
+ deps.onStatus({ message: "Reusing stored EvalOps agent API key" });
320
+ }
321
+ deps.onStatus({ message: "Registering Maestro with EvalOps agent MCP" });
322
+ let registerOutput;
323
+ try {
324
+ registerOutput = await registerAgent(options, endpoint.endpoint, apiKey, deps.createMcpClient);
325
+ }
326
+ catch (error) {
327
+ if (apiKeyCreated) {
328
+ throw error;
329
+ }
330
+ deps.onStatus({
331
+ message: "Stored EvalOps agent API key failed; rotating and retrying",
332
+ });
333
+ keyOutput = await createAgentAPIKey({ ...options, rotateKey: true }, endpoint.endpoint, oauthToken, deps.createMcpClient, now);
334
+ apiKey = keyOutput.api_key;
335
+ apiKeyCreated = true;
336
+ registerOutput = await registerAgent(options, endpoint.endpoint, apiKey, deps.createMcpClient);
337
+ }
338
+ const credentials = deps.loadCredentials("evalops");
339
+ if (!credentials) {
340
+ throw new Error("EvalOps OAuth credentials disappeared during init");
341
+ }
342
+ const keyPrefix = nonEmptyString(keyOutput?.prefix) ?? stored?.keyPrefix;
343
+ const scopes = keyOutput?.scopes ?? stored?.scopes;
344
+ const agentMcp = {
345
+ type: "agent-mcp",
346
+ apiKey,
347
+ createdAt: (apiKeyCreated
348
+ ? now
349
+ : new Date(stored?.createdAt ?? now)).toISOString(),
350
+ endpoint: endpoint.endpoint,
351
+ registeredAt: deps.now().toISOString(),
352
+ surface: options.surface ?? DEFAULT_SURFACE,
353
+ agentId: registerOutput.agent_id,
354
+ expiresAt: nonEmptyString(keyOutput?.expires_at) ?? stored?.expiresAt,
355
+ keyId: nonEmptyString(keyOutput?.key_id) ?? stored?.keyId,
356
+ keyName: nonEmptyString(keyOutput?.name) ?? stored?.keyName,
357
+ keyPrefix,
358
+ manifestUrl: endpoint.manifestUrl,
359
+ registryVisible: registerOutput.registry_visible,
360
+ runId: registerOutput.run_id,
361
+ scopes,
362
+ sessionExpiresAt: registerOutput.expires_at,
363
+ workspaceId: options.workspaceId ?? organizationIdFromCredentials(credentials),
364
+ };
365
+ saveBootstrapMetadata(credentials, agentMcp, deps.saveCredentials);
366
+ return {
367
+ agentId: registerOutput.agent_id,
368
+ apiKeyCreated,
369
+ endpoint: endpoint.endpoint,
370
+ keyPrefix,
371
+ manifestUrl: endpoint.manifestUrl,
372
+ organizationId: organizationIdFromCredentials(credentials),
373
+ registryVisible: registerOutput.registry_visible,
374
+ runId: registerOutput.run_id,
375
+ scopesGranted: registerOutput.scopes_granted,
376
+ sessionExpiresAt: registerOutput.expires_at,
377
+ stored: true,
378
+ };
379
+ }
380
+ //# sourceMappingURL=agent-bootstrap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-bootstrap.js","sourceRoot":"","sources":["../../src/evalops/agent-bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AAEnG,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAEN,oBAAoB,EACpB,oBAAoB,GACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEtE,MAAM,0BAA0B,GAAG,yBAAyB,CAAC;AAC7D,MAAM,uBAAuB,GAAG,qCAAqC,CAAC;AACtE,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,MAAM,kBAAkB,GAAG,SAAS,CAAC;AACrC,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,MAAM,uBAAuB,GAAG,CAAC,oBAAoB,CAAC,CAAC;AACvD,MAAM,sBAAsB,GAAG;IAC9B,gBAAgB;IAChB,iBAAiB;IACjB,qBAAqB;IACrB,eAAe;IACf,cAAc;CACd,CAAC;AAsGF,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,K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jC,eAAe,EAAE,cAAc,CAAC,gBAAgB;QAChD,KAAK,EAAE,cAAc,CAAC,MAAM;QAC5B,MAAM;QACN,gBAAgB,EAAE,cAAc,CAAC,UAAU;QAC3C,WAAW,EACV,OAAO,CAAC,WAAW,IAAI,6BAA6B,CAAC,WAAW,CAAC;KAClE,CAAC;IACF,qBAAqB,CAAC,WAAW,EAAE,QAAQ,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;IAEnE,OAAO;QACN,OAAO,EAAE,cAAc,CAAC,QAAQ;QAChC,aAAa;QACb,QAAQ,EAAE,QAAQ,CAAC,QAAQ;QAC3B,SAAS;QACT,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,cAAc,EAAE,6BAA6B,CAAC,WAAW,CAAC;QAC1D,eAAe,EAAE,cAAc,CAAC,gBAAgB;QAChD,KAAK,EAAE,cAAc,CAAC,MAAM;QAC5B,aAAa,EAAE,cAAc,CAAC,cAAc;QAC5C,gBAAgB,EAAE,cAAc,CAAC,UAAU;QAC3C,MAAM,EAAE,IAAI;KACZ,CAAC;AACH,CAAC","sourcesContent":["import { hostname } from \"node:os\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { getOAuthToken, hasOAuthCredentials, login } from \"../oauth/index.js\";\nimport {\n\ttype OAuthCredentials,\n\tloadOAuthCredentials,\n\tsaveOAuthCredentials,\n} from \"../oauth/storage.js\";\nimport { getPackageVersion } from \"../package-metadata.js\";\nimport { getEnvValue, normalizeBaseUrl } from \"../platform/client.js\";\n\nconst DEFAULT_AGENT_MCP_BASE_URL = \"https://app.evalops.dev\";\nconst AGENT_MCP_MANIFEST_PATH = \"/.well-known/evalops/agent-mcp.json\";\nconst AGENT_MCP_PATH = \"/mcp\";\nconst DEFAULT_AGENT_TYPE = \"maestro\";\nconst DEFAULT_SURFACE = \"cli\";\nconst DEFAULT_REGISTER_SCOPES = [\"llm_gateway:invoke\"];\nconst DEFAULT_API_KEY_SCOPES = [\n\t\"agent:register\",\n\t\"agent:heartbeat\",\n\t\"governance:evaluate\",\n\t\"memories:read\",\n\t\"meter:record\",\n];\n\nexport interface EvalOpsInitOptions {\n\tagentType?: string;\n\tapiKeyScopes?: string[];\n\texpiresInDays?: number;\n\tforceLogin?: boolean;\n\tjson?: boolean;\n\tkeyName?: string;\n\tmanifestUrl?: string;\n\tmcpUrl?: string;\n\tregisterScopes?: string[];\n\trotateKey?: boolean;\n\tsurface?: string;\n\tttlSeconds?: number;\n\tworkspaceId?: string;\n}\n\nexport interface EvalOpsAgentMcpMetadata {\n\tagentId?: string;\n\tapiKey?: string;\n\tcreatedAt: string;\n\tendpoint: string;\n\texpiresAt?: string;\n\tkeyId?: string;\n\tkeyName?: string;\n\tkeyPrefix?: string;\n\tmanifestUrl?: string;\n\tregisteredAt: string;\n\tregistryVisible?: boolean;\n\trunId?: string;\n\tscopes?: string[];\n\tsessionExpiresAt?: string;\n\tsurface: string;\n\ttype: \"agent-mcp\";\n\tworkspaceId?: string;\n}\n\nexport interface EvalOpsInitResult {\n\tagentId?: string;\n\tapiKeyCreated: boolean;\n\tendpoint: string;\n\tkeyPrefix?: string;\n\tmanifestUrl?: string;\n\torganizationId?: string;\n\tregistryVisible?: boolean;\n\trunId?: string;\n\tscopesGranted?: string[];\n\tsessionExpiresAt?: string;\n\tstored: boolean;\n}\n\nexport interface EvalOpsInitStatus {\n\tmessage: string;\n}\n\nexport interface EvalOpsInitDependencies {\n\tcreateMcpClient?: (endpoint: string, bearerToken: string) => EvalOpsMcpClient;\n\tfetch?: typeof fetch;\n\tgetOAuthToken?: typeof getOAuthToken;\n\thasOAuthCredentials?: typeof hasOAuthCredentials;\n\tloadCredentials?: typeof loadOAuthCredentials;\n\tlogin?: typeof login;\n\tnow?: () => Date;\n\tonAuthUrl?: (url: string) => void;\n\tonStatus?: (status: EvalOpsInitStatus) => void;\n\tsaveCredentials?: typeof saveOAuthCredentials;\n}\n\nexport interface EvalOpsMcpClient {\n\tcallTool(\n\t\tname: string,\n\t\targs: Record<string, unknown>,\n\t): Promise<CallToolResult>;\n\tclose(): Promise<void>;\n\tconnect(): Promise<void>;\n}\n\ninterface CreateAPIKeyOutput {\n\tapi_key: string;\n\texpires_at?: string;\n\tkey_id?: string;\n\tname?: string;\n\tprefix?: string;\n\tscopes?: string[];\n}\n\ninterface RegisterOutput {\n\tagent_id?: string;\n\texpires_at?: string;\n\tregistered?: boolean;\n\tregistry_visible?: boolean;\n\trun_id?: string;\n\tscopes_denied?: string[];\n\tscopes_granted?: string[];\n}\n\ninterface AgentMcpEndpoint {\n\tendpoint: string;\n\tmanifestUrl?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.trim().length > 0\n\t\t? value.trim()\n\t\t: undefined;\n}\n\nfunction stringArray(value: unknown): string[] | undefined {\n\tif (!Array.isArray(value)) {\n\t\treturn undefined;\n\t}\n\tconst values = value\n\t\t.map((entry) => nonEmptyString(entry))\n\t\t.filter((entry): entry is string => Boolean(entry));\n\treturn values.length > 0 ? values : undefined;\n}\n\nfunction positiveInteger(value: number | undefined): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0\n\t\t? value\n\t\t: undefined;\n}\n\nfunction getStoredAgentMcpMetadata(\n\tcredentials: OAuthCredentials | null,\n): EvalOpsAgentMcpMetadata | undefined {\n\tconst metadata = credentials?.metadata;\n\tconst agentMcp = isRecord(metadata?.agentMcp) ? metadata.agentMcp : undefined;\n\tconst apiKey = nonEmptyString(agentMcp?.apiKey);\n\tconst endpoint = nonEmptyString(agentMcp?.endpoint);\n\tconst registeredAt = nonEmptyString(agentMcp?.registeredAt);\n\tconst createdAt = nonEmptyString(agentMcp?.createdAt);\n\tconst surface = nonEmptyString(agentMcp?.surface);\n\tif (!apiKey || !endpoint || !registeredAt || !createdAt || !surface) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\ttype: \"agent-mcp\",\n\t\tapiKey,\n\t\tcreatedAt,\n\t\tendpoint,\n\t\tregisteredAt,\n\t\tsurface,\n\t\tagentId: nonEmptyString(agentMcp?.agentId),\n\t\texpiresAt: nonEmptyString(agentMcp?.expiresAt),\n\t\tkeyId: nonEmptyString(agentMcp?.keyId),\n\t\tkeyName: nonEmptyString(agentMcp?.keyName),\n\t\tkeyPrefix: nonEmptyString(agentMcp?.keyPrefix),\n\t\tmanifestUrl: nonEmptyString(agentMcp?.manifestUrl),\n\t\tregistryVisible:\n\t\t\ttypeof agentMcp?.registryVisible === \"boolean\"\n\t\t\t\t? agentMcp.registryVisible\n\t\t\t\t: undefined,\n\t\trunId: nonEmptyString(agentMcp?.runId),\n\t\tscopes: stringArray(agentMcp?.scopes),\n\t\tsessionExpiresAt: nonEmptyString(agentMcp?.sessionExpiresAt),\n\t\tworkspaceId: nonEmptyString(agentMcp?.workspaceId),\n\t};\n}\n\nexport function getStoredEvalOpsAgentMcpMetadata():\n\t| EvalOpsAgentMcpMetadata\n\t| undefined {\n\treturn getStoredAgentMcpMetadata(loadOAuthCredentials(\"evalops\"));\n}\n\nfunction normalizeMcpEndpoint(url: string): string {\n\tconst normalized = normalizeBaseUrl(url);\n\tconst parsed = new URL(normalized);\n\tif (\n\t\tparsed.pathname === \"\" ||\n\t\tparsed.pathname === \"/\" ||\n\t\tparsed.pathname === AGENT_MCP_MANIFEST_PATH\n\t) {\n\t\tparsed.pathname = AGENT_MCP_PATH;\n\t\tparsed.search = \"\";\n\t\tparsed.hash = \"\";\n\t}\n\treturn normalizeBaseUrl(parsed.toString());\n}\n\nfunction normalizeManifestUrl(url: string): string {\n\tconst normalized = normalizeBaseUrl(url);\n\tconst parsed = new URL(normalized);\n\tif (parsed.pathname === \"\" || parsed.pathname === \"/\") {\n\t\tparsed.pathname = AGENT_MCP_MANIFEST_PATH;\n\t}\n\treturn parsed.toString();\n}\n\nasync function resolveEndpointFromManifest(\n\tmanifestUrl: string,\n\tfetchImpl: typeof fetch,\n): Promise<AgentMcpEndpoint> {\n\tconst response = await fetchImpl(manifestUrl, {\n\t\theaders: { accept: \"application/json\" },\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Failed to fetch EvalOps MCP manifest (${response.status} ${response.statusText})`,\n\t\t);\n\t}\n\tconst payload = (await response.json()) as unknown;\n\tconst protocol =\n\t\tisRecord(payload) && isRecord(payload.protocol)\n\t\t\t? payload.protocol\n\t\t\t: undefined;\n\tconst endpoint = nonEmptyString(protocol?.endpoint);\n\tif (!endpoint) {\n\t\tthrow new Error(\"EvalOps MCP manifest did not include protocol.endpoint\");\n\t}\n\treturn { endpoint: normalizeMcpEndpoint(endpoint), manifestUrl };\n}\n\nasync function resolveAgentMcpEndpoint(\n\toptions: EvalOpsInitOptions,\n\tdeps: Required<Pick<EvalOpsInitDependencies, \"fetch\" | \"loadCredentials\">>,\n): Promise<AgentMcpEndpoint> {\n\tif (options.mcpUrl) {\n\t\treturn { endpoint: normalizeMcpEndpoint(options.mcpUrl) };\n\t}\n\tif (options.manifestUrl) {\n\t\treturn resolveEndpointFromManifest(\n\t\t\tnormalizeManifestUrl(options.manifestUrl),\n\t\t\tdeps.fetch,\n\t\t);\n\t}\n\n\tconst configuredMcpUrl = getEnvValue([\n\t\t\"MAESTRO_PLATFORM_MCP_URL\",\n\t\t\"MAESTRO_AGENT_MCP_URL\",\n\t\t\"MAESTRO_EVALOPS_AGENT_MCP_URL\",\n\t]);\n\tif (configuredMcpUrl) {\n\t\treturn { endpoint: normalizeMcpEndpoint(configuredMcpUrl) };\n\t}\n\n\tconst configuredManifestUrl = getEnvValue([\n\t\t\"MAESTRO_PLATFORM_MCP_MANIFEST_URL\",\n\t\t\"MAESTRO_AGENT_MCP_MANIFEST_URL\",\n\t\t\"MAESTRO_EVALOPS_AGENT_MCP_MANIFEST_URL\",\n\t]);\n\tif (configuredManifestUrl) {\n\t\treturn resolveEndpointFromManifest(\n\t\t\tnormalizeManifestUrl(configuredManifestUrl),\n\t\t\tdeps.fetch,\n\t\t);\n\t}\n\n\tconst stored = getStoredAgentMcpMetadata(deps.loadCredentials(\"evalops\"));\n\tif (stored?.endpoint) {\n\t\treturn {\n\t\t\tendpoint: normalizeMcpEndpoint(stored.endpoint),\n\t\t\tmanifestUrl: stored.manifestUrl,\n\t\t};\n\t}\n\n\treturn resolveEndpointFromManifest(\n\t\t`${DEFAULT_AGENT_MCP_BASE_URL}${AGENT_MCP_MANIFEST_PATH}`,\n\t\tdeps.fetch,\n\t);\n}\n\nfunction createDefaultMcpClient(\n\tendpoint: string,\n\tbearerToken: string,\n): EvalOpsMcpClient {\n\tconst client = new Client(\n\t\t{\n\t\t\tname: \"maestro\",\n\t\t\tversion: getPackageVersion(),\n\t\t},\n\t\t{\n\t\t\tcapabilities: {},\n\t\t},\n\t);\n\tconst headers = {\n\t\taccept: \"application/json, text/event-stream\",\n\t\t\"content-type\": \"application/json\",\n\t\t...(bearerToken ? { authorization: `Bearer ${bearerToken}` } : {}),\n\t};\n\tconst transport = new StreamableHTTPClientTransport(new URL(endpoint), {\n\t\trequestInit: {\n\t\t\theaders,\n\t\t},\n\t});\n\treturn {\n\t\tcallTool: (name, args) =>\n\t\t\tclient.callTool({\n\t\t\t\tname,\n\t\t\t\targuments: args,\n\t\t\t}) as Promise<CallToolResult>,\n\t\tclose: () => client.close(),\n\t\tconnect: () => client.connect(transport),\n\t};\n}\n\nasync function callMcpTool<T>(\n\tcreateClient: (endpoint: string, bearerToken: string) => EvalOpsMcpClient,\n\tendpoint: string,\n\ttoken: string,\n\ttoolName: string,\n\targs: Record<string, unknown>,\n): Promise<T> {\n\tconst client = createClient(endpoint, token);\n\tawait client.connect();\n\ttry {\n\t\tconst result = await client.callTool(toolName, args);\n\t\tif (result.isError) {\n\t\t\tthrow new Error(`${toolName} returned an MCP error`);\n\t\t}\n\t\treturn parseToolOutput<T>(toolName, result);\n\t} finally {\n\t\tawait client.close().catch(() => undefined);\n\t}\n}\n\nfunction parseToolOutput<T>(toolName: string, result: CallToolResult): T {\n\tconst structuredContent = isRecord(result.structuredContent)\n\t\t? result.structuredContent\n\t\t: undefined;\n\tif (structuredContent) {\n\t\treturn structuredContent as T;\n\t}\n\tconst text = Array.isArray(result.content)\n\t\t? result.content\n\t\t\t\t.map((entry) =>\n\t\t\t\t\tentry.type === \"text\" && typeof entry.text === \"string\"\n\t\t\t\t\t\t? entry.text\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\t.find((entry): entry is string => Boolean(entry))\n\t\t: undefined;\n\tif (text) {\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\tif (isRecord(parsed)) {\n\t\t\treturn parsed as T;\n\t\t}\n\t}\n\tthrow new Error(`${toolName} did not return structured JSON output`);\n}\n\nasync function ensureEvalOpsLogin(\n\toptions: EvalOpsInitOptions,\n\tdeps: Required<\n\t\tPick<\n\t\t\tEvalOpsInitDependencies,\n\t\t\t| \"getOAuthToken\"\n\t\t\t| \"hasOAuthCredentials\"\n\t\t\t| \"login\"\n\t\t\t| \"onAuthUrl\"\n\t\t\t| \"onStatus\"\n\t\t>\n\t>,\n): Promise<string> {\n\tif (options.forceLogin || !deps.hasOAuthCredentials(\"evalops\")) {\n\t\tdeps.onStatus({ message: \"Opening EvalOps login\" });\n\t\tawait deps.login(\"evalops\", {\n\t\t\tonAuthUrl: deps.onAuthUrl,\n\t\t\tonStatus: (message) => deps.onStatus({ message }),\n\t\t});\n\t}\n\n\tlet token = await deps.getOAuthToken(\"evalops\");\n\tif (!token) {\n\t\tdeps.onStatus({ message: \"Refreshing EvalOps login\" });\n\t\tawait deps.login(\"evalops\", {\n\t\t\tonAuthUrl: deps.onAuthUrl,\n\t\t\tonStatus: (message) => deps.onStatus({ message }),\n\t\t});\n\t\ttoken = await deps.getOAuthToken(\"evalops\");\n\t}\n\tif (!token) {\n\t\tthrow new Error(\"EvalOps login did not produce an access token\");\n\t}\n\treturn token;\n}\n\nfunction buildKeyName(options: EvalOpsInitOptions, now: Date): string {\n\tif (options.keyName?.trim()) {\n\t\treturn options.keyName.trim();\n\t}\n\tconst host = hostname()\n\t\t.replace(/[^a-zA-Z0-9._-]+/gu, \"-\")\n\t\t.slice(0, 48);\n\treturn `maestro-init-${host || \"local\"}-${now.toISOString().slice(0, 10)}`;\n}\n\nasync function createAgentAPIKey(\n\toptions: EvalOpsInitOptions,\n\tendpoint: string,\n\toauthToken: string,\n\tcreateClient: (endpoint: string, bearerToken: string) => EvalOpsMcpClient,\n\tnow: Date,\n): Promise<CreateAPIKeyOutput> {\n\tconst output = await callMcpTool<CreateAPIKeyOutput>(\n\t\tcreateClient,\n\t\tendpoint,\n\t\t\"\",\n\t\t\"evalops_create_api_key\",\n\t\t{\n\t\t\tname: buildKeyName(options, now),\n\t\t\tscopes: options.apiKeyScopes ?? DEFAULT_API_KEY_SCOPES,\n\t\t\tuser_token: oauthToken,\n\t\t\t...(positiveInteger(options.expiresInDays)\n\t\t\t\t? { expires_in_days: options.expiresInDays }\n\t\t\t\t: {}),\n\t\t},\n\t);\n\tif (!nonEmptyString(output.api_key)) {\n\t\tthrow new Error(\"EvalOps API key creation did not return api_key\");\n\t}\n\treturn output;\n}\n\nasync function registerAgent(\n\toptions: EvalOpsInitOptions,\n\tendpoint: string,\n\tapiKey: string,\n\tcreateClient: (endpoint: string, bearerToken: string) => EvalOpsMcpClient,\n): Promise<RegisterOutput> {\n\tconst output = await callMcpTool<RegisterOutput>(\n\t\tcreateClient,\n\t\tendpoint,\n\t\t\"\",\n\t\t\"evalops_register\",\n\t\t{\n\t\t\tagent_type: options.agentType ?? DEFAULT_AGENT_TYPE,\n\t\t\tcapabilities: [\"maestro:init\", \"maestro:cli\"],\n\t\t\tscopes: options.registerScopes ?? DEFAULT_REGISTER_SCOPES,\n\t\t\tsurface: options.surface ?? DEFAULT_SURFACE,\n\t\t\tuser_token: apiKey,\n\t\t\t...(positiveInteger(options.ttlSeconds)\n\t\t\t\t? { ttl_seconds: options.ttlSeconds }\n\t\t\t\t: {}),\n\t\t\t...(options.workspaceId ? { workspace_id: options.workspaceId } : {}),\n\t\t},\n\t);\n\tif (output.registered !== true || !nonEmptyString(output.agent_id)) {\n\t\tthrow new Error(\"EvalOps agent registration did not return an agent_id\");\n\t}\n\treturn output;\n}\n\nfunction organizationIdFromCredentials(\n\tcredentials: OAuthCredentials | null,\n): string | undefined {\n\treturn (\n\t\tnonEmptyString(credentials?.metadata?.organizationId) ??\n\t\tnonEmptyString(credentials?.metadata?.organization_id)\n\t);\n}\n\nfunction saveBootstrapMetadata(\n\tcredentials: OAuthCredentials,\n\tagentMcp: EvalOpsAgentMcpMetadata,\n\tsaveCredentials: typeof saveOAuthCredentials,\n): void {\n\tsaveCredentials(\"evalops\", {\n\t\t...credentials,\n\t\tmetadata: {\n\t\t\t...credentials.metadata,\n\t\t\tagentId: agentMcp.agentId ?? credentials.metadata?.agentId,\n\t\t\trunId: agentMcp.runId ?? credentials.metadata?.runId,\n\t\t\tsurface: agentMcp.surface,\n\t\t\tagentMcp,\n\t\t},\n\t});\n}\n\nexport async function bootstrapEvalOpsAgent(\n\toptions: EvalOpsInitOptions = {},\n\tdependencies: EvalOpsInitDependencies = {},\n): Promise<EvalOpsInitResult> {\n\tconst deps = {\n\t\tcreateMcpClient: dependencies.createMcpClient ?? createDefaultMcpClient,\n\t\tfetch: dependencies.fetch ?? fetch,\n\t\tgetOAuthToken: dependencies.getOAuthToken ?? getOAuthToken,\n\t\thasOAuthCredentials:\n\t\t\tdependencies.hasOAuthCredentials ?? hasOAuthCredentials,\n\t\tloadCredentials: dependencies.loadCredentials ?? loadOAuthCredentials,\n\t\tlogin: dependencies.login ?? login,\n\t\tnow: dependencies.now ?? (() => new Date()),\n\t\tonAuthUrl:\n\t\t\tdependencies.onAuthUrl ??\n\t\t\t((url: string) => {\n\t\t\t\tprocess.stdout.write(`${url}\\n`);\n\t\t\t}),\n\t\tonStatus: dependencies.onStatus ?? (() => undefined),\n\t\tsaveCredentials: dependencies.saveCredentials ?? saveOAuthCredentials,\n\t};\n\n\tconst oauthToken = await ensureEvalOpsLogin(options, deps);\n\tconst endpoint = await resolveAgentMcpEndpoint(options, deps);\n\tconst credentialsBeforeKey = deps.loadCredentials(\"evalops\");\n\tconst stored = getStoredAgentMcpMetadata(credentialsBeforeKey);\n\tconst now = deps.now();\n\n\tlet apiKey = stored && !options.rotateKey ? stored.apiKey : undefined;\n\tlet keyOutput: CreateAPIKeyOutput | undefined;\n\tlet apiKeyCreated = false;\n\n\tif (!apiKey) {\n\t\tdeps.onStatus({ message: \"Creating EvalOps agent API key\" });\n\t\tkeyOutput = await createAgentAPIKey(\n\t\t\toptions,\n\t\t\tendpoint.endpoint,\n\t\t\toauthToken,\n\t\t\tdeps.createMcpClient,\n\t\t\tnow,\n\t\t);\n\t\tapiKey = keyOutput.api_key;\n\t\tapiKeyCreated = true;\n\t} else {\n\t\tdeps.onStatus({ message: \"Reusing stored EvalOps agent API key\" });\n\t}\n\n\tdeps.onStatus({ message: \"Registering Maestro with EvalOps agent MCP\" });\n\tlet registerOutput: RegisterOutput;\n\ttry {\n\t\tregisterOutput = await registerAgent(\n\t\t\toptions,\n\t\t\tendpoint.endpoint,\n\t\t\tapiKey,\n\t\t\tdeps.createMcpClient,\n\t\t);\n\t} catch (error) {\n\t\tif (apiKeyCreated) {\n\t\t\tthrow error;\n\t\t}\n\t\tdeps.onStatus({\n\t\t\tmessage: \"Stored EvalOps agent API key failed; rotating and retrying\",\n\t\t});\n\t\tkeyOutput = await createAgentAPIKey(\n\t\t\t{ ...options, rotateKey: true },\n\t\t\tendpoint.endpoint,\n\t\t\toauthToken,\n\t\t\tdeps.createMcpClient,\n\t\t\tnow,\n\t\t);\n\t\tapiKey = keyOutput.api_key;\n\t\tapiKeyCreated = true;\n\t\tregisterOutput = await registerAgent(\n\t\t\toptions,\n\t\t\tendpoint.endpoint,\n\t\t\tapiKey,\n\t\t\tdeps.createMcpClient,\n\t\t);\n\t}\n\n\tconst credentials = deps.loadCredentials(\"evalops\");\n\tif (!credentials) {\n\t\tthrow new Error(\"EvalOps OAuth credentials disappeared during init\");\n\t}\n\tconst keyPrefix = nonEmptyString(keyOutput?.prefix) ?? stored?.keyPrefix;\n\tconst scopes = keyOutput?.scopes ?? stored?.scopes;\n\tconst agentMcp: EvalOpsAgentMcpMetadata = {\n\t\ttype: \"agent-mcp\",\n\t\tapiKey,\n\t\tcreatedAt: (apiKeyCreated\n\t\t\t? now\n\t\t\t: new Date(stored?.createdAt ?? now)\n\t\t).toISOString(),\n\t\tendpoint: endpoint.endpoint,\n\t\tregisteredAt: deps.now().toISOString(),\n\t\tsurface: options.surface ?? DEFAULT_SURFACE,\n\t\tagentId: registerOutput.agent_id,\n\t\texpiresAt: nonEmptyString(keyOutput?.expires_at) ?? stored?.expiresAt,\n\t\tkeyId: nonEmptyString(keyOutput?.key_id) ?? stored?.keyId,\n\t\tkeyName: nonEmptyString(keyOutput?.name) ?? stored?.keyName,\n\t\tkeyPrefix,\n\t\tmanifestUrl: endpoint.manifestUrl,\n\t\tregistryVisible: registerOutput.registry_visible,\n\t\trunId: registerOutput.run_id,\n\t\tscopes,\n\t\tsessionExpiresAt: registerOutput.expires_at,\n\t\tworkspaceId:\n\t\t\toptions.workspaceId ?? organizationIdFromCredentials(credentials),\n\t};\n\tsaveBootstrapMetadata(credentials, agentMcp, deps.saveCredentials);\n\n\treturn {\n\t\tagentId: registerOutput.agent_id,\n\t\tapiKeyCreated,\n\t\tendpoint: endpoint.endpoint,\n\t\tkeyPrefix,\n\t\tmanifestUrl: endpoint.manifestUrl,\n\t\torganizationId: organizationIdFromCredentials(credentials),\n\t\tregistryVisible: registerOutput.registry_visible,\n\t\trunId: registerOutput.run_id,\n\t\tscopesGranted: registerOutput.scopes_granted,\n\t\tsessionExpiresAt: registerOutput.expires_at,\n\t\tstored: true,\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuFG;AA4TH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,iBA69BxC"}
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuFG;AA4TH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,iBAm+BxC"}
package/dist/main.js CHANGED
@@ -576,6 +576,11 @@ export async function main(args) {
576
576
  await handleEvalOpsCommand(parsed.subcommand);
577
577
  return;
578
578
  }
579
+ if (parsed.command === "init") {
580
+ const { handleInitCommand } = await import("./cli/commands/init.js");
581
+ await handleInitCommand(parsed.commandArgs ?? []);
582
+ return;
583
+ }
579
584
  if (parsed.command === "codex") {
580
585
  const { handleCodexCommand } = await import("./cli/commands/codex.js");
581
586
  await handleCodexCommand(parsed.subcommand, parsed.messages);