-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
103 lines (95 loc) · 2.59 KB
/
Copy pathindex.ts
File metadata and controls
103 lines (95 loc) · 2.59 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
import {
OneCLIError,
OneCLIRequestError,
toOneCLIError,
} from "../errors.js";
import type {
CreateAgentInput,
CreateAgentResponse,
EnsureAgentResponse,
} from "./types.js";
import type { RequestOptions } from "../request-options.js";
export class AgentsClient {
private baseUrl: string;
private apiKey: string;
private timeout: number;
private defaultProjectId: string | null;
constructor(
baseUrl: string,
apiKey: string,
timeout: number,
defaultProjectId: string | null,
) {
this.baseUrl = baseUrl.replace(/\/+$/, "");
this.apiKey = apiKey;
this.timeout = timeout;
this.defaultProjectId = defaultProjectId;
}
private buildHeaders(options?: RequestOptions): Record<string, string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
const projectId = options?.projectId ?? this.defaultProjectId;
if (projectId) {
headers["X-Project-Id"] = projectId;
}
return headers;
}
/**
* Create a new agent.
*/
createAgent = async (
input: CreateAgentInput,
options?: RequestOptions,
): Promise<CreateAgentResponse> => {
const url = `${this.baseUrl}/api/agents`;
try {
const res = await fetch(url, {
method: "POST",
headers: this.buildHeaders(options),
body: JSON.stringify(input),
signal: AbortSignal.timeout(this.timeout),
});
if (!res.ok) {
throw new OneCLIRequestError(
`OneCLI returned ${res.status} ${res.statusText}`,
{ url, statusCode: res.status },
);
}
return (await res.json()) as CreateAgentResponse;
} catch (error) {
if (
error instanceof OneCLIError ||
error instanceof OneCLIRequestError
) {
throw error;
}
throw toOneCLIError(error);
}
};
/**
* Ensure an agent exists. Creates it if missing, returns normally if it already exists.
* Unlike `createAgent`, this method treats a 409 conflict as success.
*/
ensureAgent = async (
input: CreateAgentInput,
options?: RequestOptions,
): Promise<EnsureAgentResponse> => {
try {
await this.createAgent(input, options);
return { name: input.name, identifier: input.identifier, created: true };
} catch (error) {
if (error instanceof OneCLIRequestError && error.statusCode === 409) {
return {
name: input.name,
identifier: input.identifier,
created: false,
};
}
throw error;
}
};
}