@meistrari/agent-sdk 0.1.0
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/LICENSE +7 -0
- package/README.md +68 -0
- package/dist/index.cjs +316 -0
- package/dist/index.d.cts +147 -0
- package/dist/index.d.mts +147 -0
- package/dist/index.d.ts +147 -0
- package/dist/index.mjs +305 -0
- package/package.json +44 -0
package/LICENSE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# @meistrari/agent-sdk
|
|
2
|
+
|
|
3
|
+
A small, publishable client for the **agent-api** sandbox execution path. It owns the
|
|
4
|
+
HTTP contract so consumers (tela, chat-app, tela-dock) don't re-implement the execute
|
|
5
|
+
request, the SSE session parser, and `vault://` reference resolution by hand.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
bun add @meistrari/agent-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { agentClient, DataTokenAuthStrategy } from '@meistrari/agent-sdk'
|
|
17
|
+
|
|
18
|
+
const client = agentClient({
|
|
19
|
+
baseUrl: 'https://agent-api.example.com',
|
|
20
|
+
authStrategy: new DataTokenAuthStrategy(dataToken),
|
|
21
|
+
vaultUrl: 'https://vault.example.com', // required only for resolveReference
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
// 1) Execute an agent
|
|
25
|
+
const { success, sessionId, error } = await client.executeAgent({
|
|
26
|
+
organizationName: 'acme',
|
|
27
|
+
repository: 'support-bot',
|
|
28
|
+
message: 'Summarize the latest tickets',
|
|
29
|
+
inputs: [{ vaultRef: 'vault://...', filename: 'tickets.csv' }],
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
// 2) Consume the session as a typed async-iterable.
|
|
33
|
+
// The server already inlines step/result Vault bytes into the stream.
|
|
34
|
+
if (success && sessionId) {
|
|
35
|
+
for await (const event of client.streamSession(sessionId, { signal })) {
|
|
36
|
+
switch (event.kind) {
|
|
37
|
+
case 'status': // pending | running | completed | failed | waiting_messages | cancelled
|
|
38
|
+
break
|
|
39
|
+
case 'steps': // live step tail
|
|
40
|
+
break
|
|
41
|
+
case 'result': // final accumulated result
|
|
42
|
+
break
|
|
43
|
+
case 'error':
|
|
44
|
+
throw new Error(event.error)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 3) Resolve a vault:// reference (e.g. an output file ref found in a result)
|
|
50
|
+
const bytes = await client.resolveReference('vault://...')
|
|
51
|
+
const stream = await client.resolveReference('vault://...', { as: 'stream' })
|
|
52
|
+
const json = await client.resolveReference<MyShape>('vault://...', { as: 'json' })
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Auth
|
|
56
|
+
|
|
57
|
+
`DataTokenAuthStrategy` sends `x-data-token` — accepted by both agent-api and Vault, so a
|
|
58
|
+
single strategy covers `executeAgent`/`streamSession` and `resolveReference`.
|
|
59
|
+
`APIKeyAuthStrategy` sends `Authorization: Bearer <apiKey>` for agent-api-only use.
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
This package mirrors `@meistrari/vault-sdk` and is published as `UNLICENSED`.
|
|
64
|
+
|
|
65
|
+
## Scope
|
|
66
|
+
|
|
67
|
+
Focused on sandbox execution: `executeAgent`, `streamSession`, and `resolveReference`.
|
|
68
|
+
Agent CRUD, legacy polling, and timelines are intentionally out of scope.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const vaultSdk = require('@meistrari/vault-sdk');
|
|
4
|
+
const zod = require('zod');
|
|
5
|
+
|
|
6
|
+
var __defProp = Object.defineProperty;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __publicField = (obj, key, value) => {
|
|
9
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
10
|
+
return value;
|
|
11
|
+
};
|
|
12
|
+
class DataTokenAuthStrategy {
|
|
13
|
+
constructor(dataToken) {
|
|
14
|
+
__publicField(this, "dataToken");
|
|
15
|
+
this.dataToken = dataToken;
|
|
16
|
+
}
|
|
17
|
+
getHeaders() {
|
|
18
|
+
return new Headers({
|
|
19
|
+
"x-data-token": this.dataToken
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
class APIKeyAuthStrategy {
|
|
24
|
+
constructor(apiKey) {
|
|
25
|
+
__publicField(this, "apiKey");
|
|
26
|
+
this.apiKey = apiKey;
|
|
27
|
+
}
|
|
28
|
+
getHeaders() {
|
|
29
|
+
return new Headers({
|
|
30
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
class FetchError extends Error {
|
|
36
|
+
constructor(message, url, method, response) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.message = message;
|
|
39
|
+
this.url = url;
|
|
40
|
+
this.method = method;
|
|
41
|
+
this.response = response;
|
|
42
|
+
this.name = "FetchError";
|
|
43
|
+
}
|
|
44
|
+
static async from(url, method, response) {
|
|
45
|
+
const jsonResponse = response.clone();
|
|
46
|
+
const textResponse = response.clone();
|
|
47
|
+
const text = await jsonResponse.json().then((json) => JSON.stringify(json, null, 2)).catch(() => textResponse.text());
|
|
48
|
+
return new FetchError(
|
|
49
|
+
`Failed to ${method} ${url}: ${response.status} ${response.statusText}:
|
|
50
|
+
${text}`,
|
|
51
|
+
url,
|
|
52
|
+
method,
|
|
53
|
+
response
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const sessionStatusSchema = zod.z.enum([
|
|
59
|
+
"pending",
|
|
60
|
+
"running",
|
|
61
|
+
"completed",
|
|
62
|
+
"failed",
|
|
63
|
+
"waiting_messages",
|
|
64
|
+
"cancelled"
|
|
65
|
+
]);
|
|
66
|
+
const vaultReferenceSchema = zod.z.string().regex(/^vault:\/\/\S+$/, "vaultRef must start with vault:// and cannot contain whitespace");
|
|
67
|
+
const agentInputSchema = zod.z.object({
|
|
68
|
+
vaultRef: vaultReferenceSchema,
|
|
69
|
+
filename: zod.z.string().min(1, "Filename is required").max(255, "Filename must be 255 characters or less"),
|
|
70
|
+
metadata: zod.z.string().max(16384, "Metadata must be 16,384 characters or less").optional()
|
|
71
|
+
}).strict();
|
|
72
|
+
const executeAgentRequestSchema = zod.z.object({
|
|
73
|
+
sessionId: zod.z.string().uuid().optional(),
|
|
74
|
+
organizationName: zod.z.string().min(1).max(200).optional(),
|
|
75
|
+
repository: zod.z.string().min(1).max(200).optional(),
|
|
76
|
+
ref: zod.z.string().max(200).optional(),
|
|
77
|
+
message: zod.z.string().min(1).max(8e5).optional(),
|
|
78
|
+
inputs: zod.z.array(agentInputSchema).optional(),
|
|
79
|
+
environmentVariables: zod.z.record(zod.z.string(), zod.z.string()).optional(),
|
|
80
|
+
recover: zod.z.boolean().optional()
|
|
81
|
+
}).strict().superRefine((data, ctx) => {
|
|
82
|
+
if (!data.sessionId) {
|
|
83
|
+
if (!data.organizationName) {
|
|
84
|
+
ctx.addIssue({ code: "custom", message: "organizationName is required for new sessions", path: ["organizationName"] });
|
|
85
|
+
}
|
|
86
|
+
if (!data.repository) {
|
|
87
|
+
ctx.addIssue({ code: "custom", message: "repository is required for new sessions", path: ["repository"] });
|
|
88
|
+
}
|
|
89
|
+
if (!data.message) {
|
|
90
|
+
ctx.addIssue({ code: "custom", message: "message is required for new sessions", path: ["message"] });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (data.recover && !data.sessionId) {
|
|
94
|
+
ctx.addIssue({ code: "custom", message: "sessionId is required when recover is true", path: ["sessionId"] });
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
const executeAgentResponseSchema = zod.z.object({
|
|
98
|
+
success: zod.z.boolean(),
|
|
99
|
+
sessionId: zod.z.string().optional(),
|
|
100
|
+
error: zod.z.string().optional()
|
|
101
|
+
});
|
|
102
|
+
const sessionStatusEventSchema = zod.z.object({
|
|
103
|
+
kind: zod.z.literal("status"),
|
|
104
|
+
sessionId: zod.z.string(),
|
|
105
|
+
status: sessionStatusSchema,
|
|
106
|
+
error: zod.z.string().optional(),
|
|
107
|
+
createdAt: zod.z.number(),
|
|
108
|
+
updatedAt: zod.z.number()
|
|
109
|
+
});
|
|
110
|
+
const sessionStepsEventSchema = zod.z.object({
|
|
111
|
+
kind: zod.z.literal("steps"),
|
|
112
|
+
sessionId: zod.z.string(),
|
|
113
|
+
status: sessionStatusSchema,
|
|
114
|
+
steps: zod.z.array(zod.z.record(zod.z.string(), zod.z.unknown())),
|
|
115
|
+
nextCursor: zod.z.number().nullable(),
|
|
116
|
+
createdAt: zod.z.number(),
|
|
117
|
+
updatedAt: zod.z.number()
|
|
118
|
+
});
|
|
119
|
+
const sessionResultEventSchema = zod.z.object({
|
|
120
|
+
kind: zod.z.literal("result"),
|
|
121
|
+
sessionId: zod.z.string(),
|
|
122
|
+
status: zod.z.enum(["completed", "waiting_messages"]),
|
|
123
|
+
result: zod.z.record(zod.z.string(), zod.z.unknown()),
|
|
124
|
+
nextCursor: zod.z.number().nullable(),
|
|
125
|
+
createdAt: zod.z.number(),
|
|
126
|
+
updatedAt: zod.z.number()
|
|
127
|
+
});
|
|
128
|
+
const sessionErrorEventSchema = zod.z.object({
|
|
129
|
+
kind: zod.z.literal("error"),
|
|
130
|
+
sessionId: zod.z.string(),
|
|
131
|
+
error: zod.z.string()
|
|
132
|
+
});
|
|
133
|
+
const sessionStreamEventSchema = zod.z.discriminatedUnion("kind", [
|
|
134
|
+
sessionStatusEventSchema,
|
|
135
|
+
sessionStepsEventSchema,
|
|
136
|
+
sessionResultEventSchema,
|
|
137
|
+
sessionErrorEventSchema
|
|
138
|
+
]);
|
|
139
|
+
const SESSION_STREAM_EVENT_KINDS = /* @__PURE__ */ new Set(["status", "steps", "result", "error"]);
|
|
140
|
+
|
|
141
|
+
function normalizeStreamBuffer(buffer) {
|
|
142
|
+
return buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
143
|
+
}
|
|
144
|
+
function isControlPayload(data) {
|
|
145
|
+
return data === "[DONE]" || data === "Stream complete";
|
|
146
|
+
}
|
|
147
|
+
function parseSseFrame(frame) {
|
|
148
|
+
let data = "";
|
|
149
|
+
let hasData = false;
|
|
150
|
+
let lineStart = 0;
|
|
151
|
+
while (lineStart <= frame.length) {
|
|
152
|
+
const lineEnd = frame.indexOf("\n", lineStart);
|
|
153
|
+
const line = lineEnd === -1 ? frame.slice(lineStart) : frame.slice(lineStart, lineEnd);
|
|
154
|
+
lineStart = lineEnd === -1 ? frame.length + 1 : lineEnd + 1;
|
|
155
|
+
if (!line || line.startsWith(":"))
|
|
156
|
+
continue;
|
|
157
|
+
const separatorIndex = line.indexOf(":");
|
|
158
|
+
const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);
|
|
159
|
+
let value = separatorIndex === -1 ? "" : line.slice(separatorIndex + 1);
|
|
160
|
+
if (value.startsWith(" "))
|
|
161
|
+
value = value.slice(1);
|
|
162
|
+
if (field === "data") {
|
|
163
|
+
data = hasData ? `${data}
|
|
164
|
+
${value}` : value;
|
|
165
|
+
hasData = true;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (!hasData)
|
|
169
|
+
return void 0;
|
|
170
|
+
if (!data || isControlPayload(data))
|
|
171
|
+
return void 0;
|
|
172
|
+
try {
|
|
173
|
+
return JSON.parse(data);
|
|
174
|
+
} catch {
|
|
175
|
+
return void 0;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function getEventKind(event) {
|
|
179
|
+
if (!event || typeof event !== "object" || !("kind" in event))
|
|
180
|
+
return null;
|
|
181
|
+
const kind = event.kind;
|
|
182
|
+
return typeof kind === "string" ? kind : null;
|
|
183
|
+
}
|
|
184
|
+
function parseKnownEvent(event) {
|
|
185
|
+
const eventKind = getEventKind(event);
|
|
186
|
+
if (!eventKind || !SESSION_STREAM_EVENT_KINDS.has(eventKind))
|
|
187
|
+
return void 0;
|
|
188
|
+
const parsed = sessionStreamEventSchema.safeParse(event);
|
|
189
|
+
if (!parsed.success)
|
|
190
|
+
throw new Error(parsed.error.message);
|
|
191
|
+
return parsed.data;
|
|
192
|
+
}
|
|
193
|
+
async function* parseSessionStream(stream) {
|
|
194
|
+
const reader = stream.getReader();
|
|
195
|
+
const decoder = new TextDecoder();
|
|
196
|
+
let buffer = "";
|
|
197
|
+
function* drainBuffer() {
|
|
198
|
+
let consumedIndex = 0;
|
|
199
|
+
while (true) {
|
|
200
|
+
const frameBoundary = buffer.indexOf("\n\n", consumedIndex);
|
|
201
|
+
if (frameBoundary === -1)
|
|
202
|
+
break;
|
|
203
|
+
const event = parseSseFrame(buffer.slice(consumedIndex, frameBoundary));
|
|
204
|
+
consumedIndex = frameBoundary + 2;
|
|
205
|
+
if (event === void 0)
|
|
206
|
+
continue;
|
|
207
|
+
const parsed = parseKnownEvent(event);
|
|
208
|
+
if (parsed)
|
|
209
|
+
yield parsed;
|
|
210
|
+
}
|
|
211
|
+
if (consumedIndex > 0)
|
|
212
|
+
buffer = buffer.slice(consumedIndex);
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
while (true) {
|
|
216
|
+
const { done, value } = await reader.read();
|
|
217
|
+
if (done)
|
|
218
|
+
break;
|
|
219
|
+
buffer += normalizeStreamBuffer(decoder.decode(value, { stream: true }));
|
|
220
|
+
yield* drainBuffer();
|
|
221
|
+
}
|
|
222
|
+
buffer += normalizeStreamBuffer(decoder.decode());
|
|
223
|
+
if (buffer.trim()) {
|
|
224
|
+
const event = parseSseFrame(buffer);
|
|
225
|
+
if (event !== void 0) {
|
|
226
|
+
const parsed = parseKnownEvent(event);
|
|
227
|
+
if (parsed)
|
|
228
|
+
yield parsed;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
buffer = "";
|
|
232
|
+
} finally {
|
|
233
|
+
reader.releaseLock();
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function agentClient(config) {
|
|
238
|
+
const baseUrl = config.baseUrl.replace(/\/+$/, "");
|
|
239
|
+
async function request(params) {
|
|
240
|
+
const url = new URL(`${baseUrl}${params.path}`);
|
|
241
|
+
if (params.query) {
|
|
242
|
+
for (const [key, value] of Object.entries(params.query))
|
|
243
|
+
url.searchParams.set(key, value);
|
|
244
|
+
}
|
|
245
|
+
const headers = new Headers(config.authStrategy.getHeaders());
|
|
246
|
+
headers.set("Accept", params.accept ?? "application/json");
|
|
247
|
+
if (params.body !== void 0)
|
|
248
|
+
headers.set("Content-Type", "application/json");
|
|
249
|
+
const response = await fetch(url, {
|
|
250
|
+
method: params.method,
|
|
251
|
+
headers,
|
|
252
|
+
body: params.body !== void 0 ? JSON.stringify(params.body) : void 0,
|
|
253
|
+
signal: params.signal
|
|
254
|
+
});
|
|
255
|
+
if (!response.ok)
|
|
256
|
+
throw await FetchError.from(url.toString(), params.method, response);
|
|
257
|
+
return response;
|
|
258
|
+
}
|
|
259
|
+
async function executeAgent(input) {
|
|
260
|
+
const body = executeAgentRequestSchema.parse(input);
|
|
261
|
+
const response = await request({
|
|
262
|
+
method: "POST",
|
|
263
|
+
path: "/v4/agents/execute",
|
|
264
|
+
body
|
|
265
|
+
});
|
|
266
|
+
return executeAgentResponseSchema.parse(await response.json());
|
|
267
|
+
}
|
|
268
|
+
async function streamSession(sessionId, options) {
|
|
269
|
+
const response = await request({
|
|
270
|
+
method: "GET",
|
|
271
|
+
path: `/v4/sessions/${encodeURIComponent(sessionId)}`,
|
|
272
|
+
query: options?.cursor !== void 0 ? { cursor: String(options.cursor) } : void 0,
|
|
273
|
+
accept: "text/event-stream, application/json",
|
|
274
|
+
signal: options?.signal
|
|
275
|
+
});
|
|
276
|
+
if (!response.body)
|
|
277
|
+
throw new Error("Agent session stream response body is missing");
|
|
278
|
+
return parseSessionStream(response.body);
|
|
279
|
+
}
|
|
280
|
+
async function resolveReference(reference, options) {
|
|
281
|
+
if (!config.vaultUrl)
|
|
282
|
+
throw new Error("vaultUrl is required in AgentClientConfig to resolve references");
|
|
283
|
+
if (!reference.startsWith("vault://"))
|
|
284
|
+
throw new Error(`Unsupported vault reference: ${reference}`);
|
|
285
|
+
const vaultConfig = { vaultUrl: config.vaultUrl, authStrategy: config.authStrategy };
|
|
286
|
+
const as = options?.as ?? "bytes";
|
|
287
|
+
if (as === "stream") {
|
|
288
|
+
const vaultFile2 = await vaultSdk.VaultFile.fromVaultReference(
|
|
289
|
+
{ reference, config: vaultConfig, download: false },
|
|
290
|
+
{ signal: options?.signal }
|
|
291
|
+
);
|
|
292
|
+
return vaultFile2.downloadStream({ signal: options?.signal });
|
|
293
|
+
}
|
|
294
|
+
const vaultFile = await vaultSdk.VaultFile.fromVaultReference(
|
|
295
|
+
{ reference, config: vaultConfig, download: true },
|
|
296
|
+
{ signal: options?.signal }
|
|
297
|
+
);
|
|
298
|
+
if (!vaultFile.content)
|
|
299
|
+
throw new Error(`Vault content missing for ${reference}`);
|
|
300
|
+
if (as === "json")
|
|
301
|
+
return JSON.parse(await vaultFile.content.text());
|
|
302
|
+
return vaultFile.content.arrayBuffer();
|
|
303
|
+
}
|
|
304
|
+
return { executeAgent, streamSession, resolveReference };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
exports.APIKeyAuthStrategy = APIKeyAuthStrategy;
|
|
308
|
+
exports.DataTokenAuthStrategy = DataTokenAuthStrategy;
|
|
309
|
+
exports.FetchError = FetchError;
|
|
310
|
+
exports.agentClient = agentClient;
|
|
311
|
+
exports.agentInputSchema = agentInputSchema;
|
|
312
|
+
exports.executeAgentRequestSchema = executeAgentRequestSchema;
|
|
313
|
+
exports.executeAgentResponseSchema = executeAgentResponseSchema;
|
|
314
|
+
exports.parseSessionStream = parseSessionStream;
|
|
315
|
+
exports.sessionStatusSchema = sessionStatusSchema;
|
|
316
|
+
exports.sessionStreamEventSchema = sessionStreamEventSchema;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
interface AuthStrategy {
|
|
4
|
+
getHeaders: () => Headers;
|
|
5
|
+
}
|
|
6
|
+
declare class DataTokenAuthStrategy implements AuthStrategy {
|
|
7
|
+
dataToken: string;
|
|
8
|
+
constructor(dataToken: string);
|
|
9
|
+
getHeaders(): Headers;
|
|
10
|
+
}
|
|
11
|
+
declare class APIKeyAuthStrategy implements AuthStrategy {
|
|
12
|
+
apiKey: string;
|
|
13
|
+
constructor(apiKey: string);
|
|
14
|
+
getHeaders(): Headers;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
declare const sessionStatusSchema: z.ZodEnum<{
|
|
18
|
+
pending: "pending";
|
|
19
|
+
running: "running";
|
|
20
|
+
completed: "completed";
|
|
21
|
+
failed: "failed";
|
|
22
|
+
waiting_messages: "waiting_messages";
|
|
23
|
+
cancelled: "cancelled";
|
|
24
|
+
}>;
|
|
25
|
+
type SessionStatus = z.infer<typeof sessionStatusSchema>;
|
|
26
|
+
declare const agentInputSchema: z.ZodObject<{
|
|
27
|
+
vaultRef: z.ZodString;
|
|
28
|
+
filename: z.ZodString;
|
|
29
|
+
metadata: z.ZodOptional<z.ZodString>;
|
|
30
|
+
}, z.core.$strict>;
|
|
31
|
+
type AgentInput = z.infer<typeof agentInputSchema>;
|
|
32
|
+
declare const executeAgentRequestSchema: z.ZodObject<{
|
|
33
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
34
|
+
organizationName: z.ZodOptional<z.ZodString>;
|
|
35
|
+
repository: z.ZodOptional<z.ZodString>;
|
|
36
|
+
ref: z.ZodOptional<z.ZodString>;
|
|
37
|
+
message: z.ZodOptional<z.ZodString>;
|
|
38
|
+
inputs: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
39
|
+
vaultRef: z.ZodString;
|
|
40
|
+
filename: z.ZodString;
|
|
41
|
+
metadata: z.ZodOptional<z.ZodString>;
|
|
42
|
+
}, z.core.$strict>>>;
|
|
43
|
+
environmentVariables: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
44
|
+
recover: z.ZodOptional<z.ZodBoolean>;
|
|
45
|
+
}, z.core.$strict>;
|
|
46
|
+
type ExecuteAgentRequest = z.infer<typeof executeAgentRequestSchema>;
|
|
47
|
+
declare const executeAgentResponseSchema: z.ZodObject<{
|
|
48
|
+
success: z.ZodBoolean;
|
|
49
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
50
|
+
error: z.ZodOptional<z.ZodString>;
|
|
51
|
+
}, z.core.$strip>;
|
|
52
|
+
type ExecuteAgentResponse = z.infer<typeof executeAgentResponseSchema>;
|
|
53
|
+
declare const sessionStreamEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
54
|
+
kind: z.ZodLiteral<"status">;
|
|
55
|
+
sessionId: z.ZodString;
|
|
56
|
+
status: z.ZodEnum<{
|
|
57
|
+
pending: "pending";
|
|
58
|
+
running: "running";
|
|
59
|
+
completed: "completed";
|
|
60
|
+
failed: "failed";
|
|
61
|
+
waiting_messages: "waiting_messages";
|
|
62
|
+
cancelled: "cancelled";
|
|
63
|
+
}>;
|
|
64
|
+
error: z.ZodOptional<z.ZodString>;
|
|
65
|
+
createdAt: z.ZodNumber;
|
|
66
|
+
updatedAt: z.ZodNumber;
|
|
67
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
68
|
+
kind: z.ZodLiteral<"steps">;
|
|
69
|
+
sessionId: z.ZodString;
|
|
70
|
+
status: z.ZodEnum<{
|
|
71
|
+
pending: "pending";
|
|
72
|
+
running: "running";
|
|
73
|
+
completed: "completed";
|
|
74
|
+
failed: "failed";
|
|
75
|
+
waiting_messages: "waiting_messages";
|
|
76
|
+
cancelled: "cancelled";
|
|
77
|
+
}>;
|
|
78
|
+
steps: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
79
|
+
nextCursor: z.ZodNullable<z.ZodNumber>;
|
|
80
|
+
createdAt: z.ZodNumber;
|
|
81
|
+
updatedAt: z.ZodNumber;
|
|
82
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
83
|
+
kind: z.ZodLiteral<"result">;
|
|
84
|
+
sessionId: z.ZodString;
|
|
85
|
+
status: z.ZodEnum<{
|
|
86
|
+
completed: "completed";
|
|
87
|
+
waiting_messages: "waiting_messages";
|
|
88
|
+
}>;
|
|
89
|
+
result: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
90
|
+
nextCursor: z.ZodNullable<z.ZodNumber>;
|
|
91
|
+
createdAt: z.ZodNumber;
|
|
92
|
+
updatedAt: z.ZodNumber;
|
|
93
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
94
|
+
kind: z.ZodLiteral<"error">;
|
|
95
|
+
sessionId: z.ZodString;
|
|
96
|
+
error: z.ZodString;
|
|
97
|
+
}, z.core.$strip>], "kind">;
|
|
98
|
+
type SessionStreamEvent = z.infer<typeof sessionStreamEventSchema>;
|
|
99
|
+
|
|
100
|
+
interface AgentClientConfig {
|
|
101
|
+
baseUrl: string;
|
|
102
|
+
authStrategy: AuthStrategy;
|
|
103
|
+
vaultUrl?: string;
|
|
104
|
+
}
|
|
105
|
+
interface StreamSessionOptions {
|
|
106
|
+
cursor?: number;
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
}
|
|
109
|
+
type ResolveReferenceAs = 'bytes' | 'stream' | 'json';
|
|
110
|
+
interface ResolveReferenceOptions {
|
|
111
|
+
as?: ResolveReferenceAs;
|
|
112
|
+
signal?: AbortSignal;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
declare function agentClient(config: AgentClientConfig): {
|
|
116
|
+
executeAgent: (input: ExecuteAgentRequest) => Promise<ExecuteAgentResponse>;
|
|
117
|
+
streamSession: (sessionId: string, options?: StreamSessionOptions) => Promise<AsyncIterable<SessionStreamEvent>>;
|
|
118
|
+
resolveReference: {
|
|
119
|
+
(reference: string, options?: {
|
|
120
|
+
as?: "bytes";
|
|
121
|
+
signal?: AbortSignal;
|
|
122
|
+
}): Promise<ArrayBuffer>;
|
|
123
|
+
(reference: string, options: {
|
|
124
|
+
as: "stream";
|
|
125
|
+
signal?: AbortSignal;
|
|
126
|
+
}): Promise<ReadableStream<Uint8Array>>;
|
|
127
|
+
<T = unknown>(reference: string, options: {
|
|
128
|
+
as: "json";
|
|
129
|
+
signal?: AbortSignal;
|
|
130
|
+
}): Promise<T>;
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
type AgentClient = ReturnType<typeof agentClient>;
|
|
134
|
+
|
|
135
|
+
declare class FetchError extends Error {
|
|
136
|
+
readonly message: string;
|
|
137
|
+
readonly url: string;
|
|
138
|
+
readonly method: string;
|
|
139
|
+
readonly response: Response;
|
|
140
|
+
constructor(message: string, url: string, method: string, response: Response);
|
|
141
|
+
static from(url: string, method: string, response: Response): Promise<FetchError>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
declare function parseSessionStream(stream: ReadableStream<Uint8Array>): AsyncIterable<SessionStreamEvent>;
|
|
145
|
+
|
|
146
|
+
export { APIKeyAuthStrategy, DataTokenAuthStrategy, FetchError, agentClient, agentInputSchema, executeAgentRequestSchema, executeAgentResponseSchema, parseSessionStream, sessionStatusSchema, sessionStreamEventSchema };
|
|
147
|
+
export type { AgentClient, AgentClientConfig, AgentInput, AuthStrategy, ExecuteAgentRequest, ExecuteAgentResponse, ResolveReferenceAs, ResolveReferenceOptions, SessionStatus, SessionStreamEvent, StreamSessionOptions };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
interface AuthStrategy {
|
|
4
|
+
getHeaders: () => Headers;
|
|
5
|
+
}
|
|
6
|
+
declare class DataTokenAuthStrategy implements AuthStrategy {
|
|
7
|
+
dataToken: string;
|
|
8
|
+
constructor(dataToken: string);
|
|
9
|
+
getHeaders(): Headers;
|
|
10
|
+
}
|
|
11
|
+
declare class APIKeyAuthStrategy implements AuthStrategy {
|
|
12
|
+
apiKey: string;
|
|
13
|
+
constructor(apiKey: string);
|
|
14
|
+
getHeaders(): Headers;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
declare const sessionStatusSchema: z.ZodEnum<{
|
|
18
|
+
pending: "pending";
|
|
19
|
+
running: "running";
|
|
20
|
+
completed: "completed";
|
|
21
|
+
failed: "failed";
|
|
22
|
+
waiting_messages: "waiting_messages";
|
|
23
|
+
cancelled: "cancelled";
|
|
24
|
+
}>;
|
|
25
|
+
type SessionStatus = z.infer<typeof sessionStatusSchema>;
|
|
26
|
+
declare const agentInputSchema: z.ZodObject<{
|
|
27
|
+
vaultRef: z.ZodString;
|
|
28
|
+
filename: z.ZodString;
|
|
29
|
+
metadata: z.ZodOptional<z.ZodString>;
|
|
30
|
+
}, z.core.$strict>;
|
|
31
|
+
type AgentInput = z.infer<typeof agentInputSchema>;
|
|
32
|
+
declare const executeAgentRequestSchema: z.ZodObject<{
|
|
33
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
34
|
+
organizationName: z.ZodOptional<z.ZodString>;
|
|
35
|
+
repository: z.ZodOptional<z.ZodString>;
|
|
36
|
+
ref: z.ZodOptional<z.ZodString>;
|
|
37
|
+
message: z.ZodOptional<z.ZodString>;
|
|
38
|
+
inputs: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
39
|
+
vaultRef: z.ZodString;
|
|
40
|
+
filename: z.ZodString;
|
|
41
|
+
metadata: z.ZodOptional<z.ZodString>;
|
|
42
|
+
}, z.core.$strict>>>;
|
|
43
|
+
environmentVariables: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
44
|
+
recover: z.ZodOptional<z.ZodBoolean>;
|
|
45
|
+
}, z.core.$strict>;
|
|
46
|
+
type ExecuteAgentRequest = z.infer<typeof executeAgentRequestSchema>;
|
|
47
|
+
declare const executeAgentResponseSchema: z.ZodObject<{
|
|
48
|
+
success: z.ZodBoolean;
|
|
49
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
50
|
+
error: z.ZodOptional<z.ZodString>;
|
|
51
|
+
}, z.core.$strip>;
|
|
52
|
+
type ExecuteAgentResponse = z.infer<typeof executeAgentResponseSchema>;
|
|
53
|
+
declare const sessionStreamEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
54
|
+
kind: z.ZodLiteral<"status">;
|
|
55
|
+
sessionId: z.ZodString;
|
|
56
|
+
status: z.ZodEnum<{
|
|
57
|
+
pending: "pending";
|
|
58
|
+
running: "running";
|
|
59
|
+
completed: "completed";
|
|
60
|
+
failed: "failed";
|
|
61
|
+
waiting_messages: "waiting_messages";
|
|
62
|
+
cancelled: "cancelled";
|
|
63
|
+
}>;
|
|
64
|
+
error: z.ZodOptional<z.ZodString>;
|
|
65
|
+
createdAt: z.ZodNumber;
|
|
66
|
+
updatedAt: z.ZodNumber;
|
|
67
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
68
|
+
kind: z.ZodLiteral<"steps">;
|
|
69
|
+
sessionId: z.ZodString;
|
|
70
|
+
status: z.ZodEnum<{
|
|
71
|
+
pending: "pending";
|
|
72
|
+
running: "running";
|
|
73
|
+
completed: "completed";
|
|
74
|
+
failed: "failed";
|
|
75
|
+
waiting_messages: "waiting_messages";
|
|
76
|
+
cancelled: "cancelled";
|
|
77
|
+
}>;
|
|
78
|
+
steps: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
79
|
+
nextCursor: z.ZodNullable<z.ZodNumber>;
|
|
80
|
+
createdAt: z.ZodNumber;
|
|
81
|
+
updatedAt: z.ZodNumber;
|
|
82
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
83
|
+
kind: z.ZodLiteral<"result">;
|
|
84
|
+
sessionId: z.ZodString;
|
|
85
|
+
status: z.ZodEnum<{
|
|
86
|
+
completed: "completed";
|
|
87
|
+
waiting_messages: "waiting_messages";
|
|
88
|
+
}>;
|
|
89
|
+
result: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
90
|
+
nextCursor: z.ZodNullable<z.ZodNumber>;
|
|
91
|
+
createdAt: z.ZodNumber;
|
|
92
|
+
updatedAt: z.ZodNumber;
|
|
93
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
94
|
+
kind: z.ZodLiteral<"error">;
|
|
95
|
+
sessionId: z.ZodString;
|
|
96
|
+
error: z.ZodString;
|
|
97
|
+
}, z.core.$strip>], "kind">;
|
|
98
|
+
type SessionStreamEvent = z.infer<typeof sessionStreamEventSchema>;
|
|
99
|
+
|
|
100
|
+
interface AgentClientConfig {
|
|
101
|
+
baseUrl: string;
|
|
102
|
+
authStrategy: AuthStrategy;
|
|
103
|
+
vaultUrl?: string;
|
|
104
|
+
}
|
|
105
|
+
interface StreamSessionOptions {
|
|
106
|
+
cursor?: number;
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
}
|
|
109
|
+
type ResolveReferenceAs = 'bytes' | 'stream' | 'json';
|
|
110
|
+
interface ResolveReferenceOptions {
|
|
111
|
+
as?: ResolveReferenceAs;
|
|
112
|
+
signal?: AbortSignal;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
declare function agentClient(config: AgentClientConfig): {
|
|
116
|
+
executeAgent: (input: ExecuteAgentRequest) => Promise<ExecuteAgentResponse>;
|
|
117
|
+
streamSession: (sessionId: string, options?: StreamSessionOptions) => Promise<AsyncIterable<SessionStreamEvent>>;
|
|
118
|
+
resolveReference: {
|
|
119
|
+
(reference: string, options?: {
|
|
120
|
+
as?: "bytes";
|
|
121
|
+
signal?: AbortSignal;
|
|
122
|
+
}): Promise<ArrayBuffer>;
|
|
123
|
+
(reference: string, options: {
|
|
124
|
+
as: "stream";
|
|
125
|
+
signal?: AbortSignal;
|
|
126
|
+
}): Promise<ReadableStream<Uint8Array>>;
|
|
127
|
+
<T = unknown>(reference: string, options: {
|
|
128
|
+
as: "json";
|
|
129
|
+
signal?: AbortSignal;
|
|
130
|
+
}): Promise<T>;
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
type AgentClient = ReturnType<typeof agentClient>;
|
|
134
|
+
|
|
135
|
+
declare class FetchError extends Error {
|
|
136
|
+
readonly message: string;
|
|
137
|
+
readonly url: string;
|
|
138
|
+
readonly method: string;
|
|
139
|
+
readonly response: Response;
|
|
140
|
+
constructor(message: string, url: string, method: string, response: Response);
|
|
141
|
+
static from(url: string, method: string, response: Response): Promise<FetchError>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
declare function parseSessionStream(stream: ReadableStream<Uint8Array>): AsyncIterable<SessionStreamEvent>;
|
|
145
|
+
|
|
146
|
+
export { APIKeyAuthStrategy, DataTokenAuthStrategy, FetchError, agentClient, agentInputSchema, executeAgentRequestSchema, executeAgentResponseSchema, parseSessionStream, sessionStatusSchema, sessionStreamEventSchema };
|
|
147
|
+
export type { AgentClient, AgentClientConfig, AgentInput, AuthStrategy, ExecuteAgentRequest, ExecuteAgentResponse, ResolveReferenceAs, ResolveReferenceOptions, SessionStatus, SessionStreamEvent, StreamSessionOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
interface AuthStrategy {
|
|
4
|
+
getHeaders: () => Headers;
|
|
5
|
+
}
|
|
6
|
+
declare class DataTokenAuthStrategy implements AuthStrategy {
|
|
7
|
+
dataToken: string;
|
|
8
|
+
constructor(dataToken: string);
|
|
9
|
+
getHeaders(): Headers;
|
|
10
|
+
}
|
|
11
|
+
declare class APIKeyAuthStrategy implements AuthStrategy {
|
|
12
|
+
apiKey: string;
|
|
13
|
+
constructor(apiKey: string);
|
|
14
|
+
getHeaders(): Headers;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
declare const sessionStatusSchema: z.ZodEnum<{
|
|
18
|
+
pending: "pending";
|
|
19
|
+
running: "running";
|
|
20
|
+
completed: "completed";
|
|
21
|
+
failed: "failed";
|
|
22
|
+
waiting_messages: "waiting_messages";
|
|
23
|
+
cancelled: "cancelled";
|
|
24
|
+
}>;
|
|
25
|
+
type SessionStatus = z.infer<typeof sessionStatusSchema>;
|
|
26
|
+
declare const agentInputSchema: z.ZodObject<{
|
|
27
|
+
vaultRef: z.ZodString;
|
|
28
|
+
filename: z.ZodString;
|
|
29
|
+
metadata: z.ZodOptional<z.ZodString>;
|
|
30
|
+
}, z.core.$strict>;
|
|
31
|
+
type AgentInput = z.infer<typeof agentInputSchema>;
|
|
32
|
+
declare const executeAgentRequestSchema: z.ZodObject<{
|
|
33
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
34
|
+
organizationName: z.ZodOptional<z.ZodString>;
|
|
35
|
+
repository: z.ZodOptional<z.ZodString>;
|
|
36
|
+
ref: z.ZodOptional<z.ZodString>;
|
|
37
|
+
message: z.ZodOptional<z.ZodString>;
|
|
38
|
+
inputs: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
39
|
+
vaultRef: z.ZodString;
|
|
40
|
+
filename: z.ZodString;
|
|
41
|
+
metadata: z.ZodOptional<z.ZodString>;
|
|
42
|
+
}, z.core.$strict>>>;
|
|
43
|
+
environmentVariables: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
44
|
+
recover: z.ZodOptional<z.ZodBoolean>;
|
|
45
|
+
}, z.core.$strict>;
|
|
46
|
+
type ExecuteAgentRequest = z.infer<typeof executeAgentRequestSchema>;
|
|
47
|
+
declare const executeAgentResponseSchema: z.ZodObject<{
|
|
48
|
+
success: z.ZodBoolean;
|
|
49
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
50
|
+
error: z.ZodOptional<z.ZodString>;
|
|
51
|
+
}, z.core.$strip>;
|
|
52
|
+
type ExecuteAgentResponse = z.infer<typeof executeAgentResponseSchema>;
|
|
53
|
+
declare const sessionStreamEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
54
|
+
kind: z.ZodLiteral<"status">;
|
|
55
|
+
sessionId: z.ZodString;
|
|
56
|
+
status: z.ZodEnum<{
|
|
57
|
+
pending: "pending";
|
|
58
|
+
running: "running";
|
|
59
|
+
completed: "completed";
|
|
60
|
+
failed: "failed";
|
|
61
|
+
waiting_messages: "waiting_messages";
|
|
62
|
+
cancelled: "cancelled";
|
|
63
|
+
}>;
|
|
64
|
+
error: z.ZodOptional<z.ZodString>;
|
|
65
|
+
createdAt: z.ZodNumber;
|
|
66
|
+
updatedAt: z.ZodNumber;
|
|
67
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
68
|
+
kind: z.ZodLiteral<"steps">;
|
|
69
|
+
sessionId: z.ZodString;
|
|
70
|
+
status: z.ZodEnum<{
|
|
71
|
+
pending: "pending";
|
|
72
|
+
running: "running";
|
|
73
|
+
completed: "completed";
|
|
74
|
+
failed: "failed";
|
|
75
|
+
waiting_messages: "waiting_messages";
|
|
76
|
+
cancelled: "cancelled";
|
|
77
|
+
}>;
|
|
78
|
+
steps: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
79
|
+
nextCursor: z.ZodNullable<z.ZodNumber>;
|
|
80
|
+
createdAt: z.ZodNumber;
|
|
81
|
+
updatedAt: z.ZodNumber;
|
|
82
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
83
|
+
kind: z.ZodLiteral<"result">;
|
|
84
|
+
sessionId: z.ZodString;
|
|
85
|
+
status: z.ZodEnum<{
|
|
86
|
+
completed: "completed";
|
|
87
|
+
waiting_messages: "waiting_messages";
|
|
88
|
+
}>;
|
|
89
|
+
result: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
90
|
+
nextCursor: z.ZodNullable<z.ZodNumber>;
|
|
91
|
+
createdAt: z.ZodNumber;
|
|
92
|
+
updatedAt: z.ZodNumber;
|
|
93
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
94
|
+
kind: z.ZodLiteral<"error">;
|
|
95
|
+
sessionId: z.ZodString;
|
|
96
|
+
error: z.ZodString;
|
|
97
|
+
}, z.core.$strip>], "kind">;
|
|
98
|
+
type SessionStreamEvent = z.infer<typeof sessionStreamEventSchema>;
|
|
99
|
+
|
|
100
|
+
interface AgentClientConfig {
|
|
101
|
+
baseUrl: string;
|
|
102
|
+
authStrategy: AuthStrategy;
|
|
103
|
+
vaultUrl?: string;
|
|
104
|
+
}
|
|
105
|
+
interface StreamSessionOptions {
|
|
106
|
+
cursor?: number;
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
}
|
|
109
|
+
type ResolveReferenceAs = 'bytes' | 'stream' | 'json';
|
|
110
|
+
interface ResolveReferenceOptions {
|
|
111
|
+
as?: ResolveReferenceAs;
|
|
112
|
+
signal?: AbortSignal;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
declare function agentClient(config: AgentClientConfig): {
|
|
116
|
+
executeAgent: (input: ExecuteAgentRequest) => Promise<ExecuteAgentResponse>;
|
|
117
|
+
streamSession: (sessionId: string, options?: StreamSessionOptions) => Promise<AsyncIterable<SessionStreamEvent>>;
|
|
118
|
+
resolveReference: {
|
|
119
|
+
(reference: string, options?: {
|
|
120
|
+
as?: "bytes";
|
|
121
|
+
signal?: AbortSignal;
|
|
122
|
+
}): Promise<ArrayBuffer>;
|
|
123
|
+
(reference: string, options: {
|
|
124
|
+
as: "stream";
|
|
125
|
+
signal?: AbortSignal;
|
|
126
|
+
}): Promise<ReadableStream<Uint8Array>>;
|
|
127
|
+
<T = unknown>(reference: string, options: {
|
|
128
|
+
as: "json";
|
|
129
|
+
signal?: AbortSignal;
|
|
130
|
+
}): Promise<T>;
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
type AgentClient = ReturnType<typeof agentClient>;
|
|
134
|
+
|
|
135
|
+
declare class FetchError extends Error {
|
|
136
|
+
readonly message: string;
|
|
137
|
+
readonly url: string;
|
|
138
|
+
readonly method: string;
|
|
139
|
+
readonly response: Response;
|
|
140
|
+
constructor(message: string, url: string, method: string, response: Response);
|
|
141
|
+
static from(url: string, method: string, response: Response): Promise<FetchError>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
declare function parseSessionStream(stream: ReadableStream<Uint8Array>): AsyncIterable<SessionStreamEvent>;
|
|
145
|
+
|
|
146
|
+
export { APIKeyAuthStrategy, DataTokenAuthStrategy, FetchError, agentClient, agentInputSchema, executeAgentRequestSchema, executeAgentResponseSchema, parseSessionStream, sessionStatusSchema, sessionStreamEventSchema };
|
|
147
|
+
export type { AgentClient, AgentClientConfig, AgentInput, AuthStrategy, ExecuteAgentRequest, ExecuteAgentResponse, ResolveReferenceAs, ResolveReferenceOptions, SessionStatus, SessionStreamEvent, StreamSessionOptions };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { VaultFile } from '@meistrari/vault-sdk';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __publicField = (obj, key, value) => {
|
|
7
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
8
|
+
return value;
|
|
9
|
+
};
|
|
10
|
+
class DataTokenAuthStrategy {
|
|
11
|
+
constructor(dataToken) {
|
|
12
|
+
__publicField(this, "dataToken");
|
|
13
|
+
this.dataToken = dataToken;
|
|
14
|
+
}
|
|
15
|
+
getHeaders() {
|
|
16
|
+
return new Headers({
|
|
17
|
+
"x-data-token": this.dataToken
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
class APIKeyAuthStrategy {
|
|
22
|
+
constructor(apiKey) {
|
|
23
|
+
__publicField(this, "apiKey");
|
|
24
|
+
this.apiKey = apiKey;
|
|
25
|
+
}
|
|
26
|
+
getHeaders() {
|
|
27
|
+
return new Headers({
|
|
28
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
class FetchError extends Error {
|
|
34
|
+
constructor(message, url, method, response) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.message = message;
|
|
37
|
+
this.url = url;
|
|
38
|
+
this.method = method;
|
|
39
|
+
this.response = response;
|
|
40
|
+
this.name = "FetchError";
|
|
41
|
+
}
|
|
42
|
+
static async from(url, method, response) {
|
|
43
|
+
const jsonResponse = response.clone();
|
|
44
|
+
const textResponse = response.clone();
|
|
45
|
+
const text = await jsonResponse.json().then((json) => JSON.stringify(json, null, 2)).catch(() => textResponse.text());
|
|
46
|
+
return new FetchError(
|
|
47
|
+
`Failed to ${method} ${url}: ${response.status} ${response.statusText}:
|
|
48
|
+
${text}`,
|
|
49
|
+
url,
|
|
50
|
+
method,
|
|
51
|
+
response
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const sessionStatusSchema = z.enum([
|
|
57
|
+
"pending",
|
|
58
|
+
"running",
|
|
59
|
+
"completed",
|
|
60
|
+
"failed",
|
|
61
|
+
"waiting_messages",
|
|
62
|
+
"cancelled"
|
|
63
|
+
]);
|
|
64
|
+
const vaultReferenceSchema = z.string().regex(/^vault:\/\/\S+$/, "vaultRef must start with vault:// and cannot contain whitespace");
|
|
65
|
+
const agentInputSchema = z.object({
|
|
66
|
+
vaultRef: vaultReferenceSchema,
|
|
67
|
+
filename: z.string().min(1, "Filename is required").max(255, "Filename must be 255 characters or less"),
|
|
68
|
+
metadata: z.string().max(16384, "Metadata must be 16,384 characters or less").optional()
|
|
69
|
+
}).strict();
|
|
70
|
+
const executeAgentRequestSchema = z.object({
|
|
71
|
+
sessionId: z.string().uuid().optional(),
|
|
72
|
+
organizationName: z.string().min(1).max(200).optional(),
|
|
73
|
+
repository: z.string().min(1).max(200).optional(),
|
|
74
|
+
ref: z.string().max(200).optional(),
|
|
75
|
+
message: z.string().min(1).max(8e5).optional(),
|
|
76
|
+
inputs: z.array(agentInputSchema).optional(),
|
|
77
|
+
environmentVariables: z.record(z.string(), z.string()).optional(),
|
|
78
|
+
recover: z.boolean().optional()
|
|
79
|
+
}).strict().superRefine((data, ctx) => {
|
|
80
|
+
if (!data.sessionId) {
|
|
81
|
+
if (!data.organizationName) {
|
|
82
|
+
ctx.addIssue({ code: "custom", message: "organizationName is required for new sessions", path: ["organizationName"] });
|
|
83
|
+
}
|
|
84
|
+
if (!data.repository) {
|
|
85
|
+
ctx.addIssue({ code: "custom", message: "repository is required for new sessions", path: ["repository"] });
|
|
86
|
+
}
|
|
87
|
+
if (!data.message) {
|
|
88
|
+
ctx.addIssue({ code: "custom", message: "message is required for new sessions", path: ["message"] });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (data.recover && !data.sessionId) {
|
|
92
|
+
ctx.addIssue({ code: "custom", message: "sessionId is required when recover is true", path: ["sessionId"] });
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
const executeAgentResponseSchema = z.object({
|
|
96
|
+
success: z.boolean(),
|
|
97
|
+
sessionId: z.string().optional(),
|
|
98
|
+
error: z.string().optional()
|
|
99
|
+
});
|
|
100
|
+
const sessionStatusEventSchema = z.object({
|
|
101
|
+
kind: z.literal("status"),
|
|
102
|
+
sessionId: z.string(),
|
|
103
|
+
status: sessionStatusSchema,
|
|
104
|
+
error: z.string().optional(),
|
|
105
|
+
createdAt: z.number(),
|
|
106
|
+
updatedAt: z.number()
|
|
107
|
+
});
|
|
108
|
+
const sessionStepsEventSchema = z.object({
|
|
109
|
+
kind: z.literal("steps"),
|
|
110
|
+
sessionId: z.string(),
|
|
111
|
+
status: sessionStatusSchema,
|
|
112
|
+
steps: z.array(z.record(z.string(), z.unknown())),
|
|
113
|
+
nextCursor: z.number().nullable(),
|
|
114
|
+
createdAt: z.number(),
|
|
115
|
+
updatedAt: z.number()
|
|
116
|
+
});
|
|
117
|
+
const sessionResultEventSchema = z.object({
|
|
118
|
+
kind: z.literal("result"),
|
|
119
|
+
sessionId: z.string(),
|
|
120
|
+
status: z.enum(["completed", "waiting_messages"]),
|
|
121
|
+
result: z.record(z.string(), z.unknown()),
|
|
122
|
+
nextCursor: z.number().nullable(),
|
|
123
|
+
createdAt: z.number(),
|
|
124
|
+
updatedAt: z.number()
|
|
125
|
+
});
|
|
126
|
+
const sessionErrorEventSchema = z.object({
|
|
127
|
+
kind: z.literal("error"),
|
|
128
|
+
sessionId: z.string(),
|
|
129
|
+
error: z.string()
|
|
130
|
+
});
|
|
131
|
+
const sessionStreamEventSchema = z.discriminatedUnion("kind", [
|
|
132
|
+
sessionStatusEventSchema,
|
|
133
|
+
sessionStepsEventSchema,
|
|
134
|
+
sessionResultEventSchema,
|
|
135
|
+
sessionErrorEventSchema
|
|
136
|
+
]);
|
|
137
|
+
const SESSION_STREAM_EVENT_KINDS = /* @__PURE__ */ new Set(["status", "steps", "result", "error"]);
|
|
138
|
+
|
|
139
|
+
function normalizeStreamBuffer(buffer) {
|
|
140
|
+
return buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
141
|
+
}
|
|
142
|
+
function isControlPayload(data) {
|
|
143
|
+
return data === "[DONE]" || data === "Stream complete";
|
|
144
|
+
}
|
|
145
|
+
function parseSseFrame(frame) {
|
|
146
|
+
let data = "";
|
|
147
|
+
let hasData = false;
|
|
148
|
+
let lineStart = 0;
|
|
149
|
+
while (lineStart <= frame.length) {
|
|
150
|
+
const lineEnd = frame.indexOf("\n", lineStart);
|
|
151
|
+
const line = lineEnd === -1 ? frame.slice(lineStart) : frame.slice(lineStart, lineEnd);
|
|
152
|
+
lineStart = lineEnd === -1 ? frame.length + 1 : lineEnd + 1;
|
|
153
|
+
if (!line || line.startsWith(":"))
|
|
154
|
+
continue;
|
|
155
|
+
const separatorIndex = line.indexOf(":");
|
|
156
|
+
const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);
|
|
157
|
+
let value = separatorIndex === -1 ? "" : line.slice(separatorIndex + 1);
|
|
158
|
+
if (value.startsWith(" "))
|
|
159
|
+
value = value.slice(1);
|
|
160
|
+
if (field === "data") {
|
|
161
|
+
data = hasData ? `${data}
|
|
162
|
+
${value}` : value;
|
|
163
|
+
hasData = true;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (!hasData)
|
|
167
|
+
return void 0;
|
|
168
|
+
if (!data || isControlPayload(data))
|
|
169
|
+
return void 0;
|
|
170
|
+
try {
|
|
171
|
+
return JSON.parse(data);
|
|
172
|
+
} catch {
|
|
173
|
+
return void 0;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function getEventKind(event) {
|
|
177
|
+
if (!event || typeof event !== "object" || !("kind" in event))
|
|
178
|
+
return null;
|
|
179
|
+
const kind = event.kind;
|
|
180
|
+
return typeof kind === "string" ? kind : null;
|
|
181
|
+
}
|
|
182
|
+
function parseKnownEvent(event) {
|
|
183
|
+
const eventKind = getEventKind(event);
|
|
184
|
+
if (!eventKind || !SESSION_STREAM_EVENT_KINDS.has(eventKind))
|
|
185
|
+
return void 0;
|
|
186
|
+
const parsed = sessionStreamEventSchema.safeParse(event);
|
|
187
|
+
if (!parsed.success)
|
|
188
|
+
throw new Error(parsed.error.message);
|
|
189
|
+
return parsed.data;
|
|
190
|
+
}
|
|
191
|
+
async function* parseSessionStream(stream) {
|
|
192
|
+
const reader = stream.getReader();
|
|
193
|
+
const decoder = new TextDecoder();
|
|
194
|
+
let buffer = "";
|
|
195
|
+
function* drainBuffer() {
|
|
196
|
+
let consumedIndex = 0;
|
|
197
|
+
while (true) {
|
|
198
|
+
const frameBoundary = buffer.indexOf("\n\n", consumedIndex);
|
|
199
|
+
if (frameBoundary === -1)
|
|
200
|
+
break;
|
|
201
|
+
const event = parseSseFrame(buffer.slice(consumedIndex, frameBoundary));
|
|
202
|
+
consumedIndex = frameBoundary + 2;
|
|
203
|
+
if (event === void 0)
|
|
204
|
+
continue;
|
|
205
|
+
const parsed = parseKnownEvent(event);
|
|
206
|
+
if (parsed)
|
|
207
|
+
yield parsed;
|
|
208
|
+
}
|
|
209
|
+
if (consumedIndex > 0)
|
|
210
|
+
buffer = buffer.slice(consumedIndex);
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
while (true) {
|
|
214
|
+
const { done, value } = await reader.read();
|
|
215
|
+
if (done)
|
|
216
|
+
break;
|
|
217
|
+
buffer += normalizeStreamBuffer(decoder.decode(value, { stream: true }));
|
|
218
|
+
yield* drainBuffer();
|
|
219
|
+
}
|
|
220
|
+
buffer += normalizeStreamBuffer(decoder.decode());
|
|
221
|
+
if (buffer.trim()) {
|
|
222
|
+
const event = parseSseFrame(buffer);
|
|
223
|
+
if (event !== void 0) {
|
|
224
|
+
const parsed = parseKnownEvent(event);
|
|
225
|
+
if (parsed)
|
|
226
|
+
yield parsed;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
buffer = "";
|
|
230
|
+
} finally {
|
|
231
|
+
reader.releaseLock();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function agentClient(config) {
|
|
236
|
+
const baseUrl = config.baseUrl.replace(/\/+$/, "");
|
|
237
|
+
async function request(params) {
|
|
238
|
+
const url = new URL(`${baseUrl}${params.path}`);
|
|
239
|
+
if (params.query) {
|
|
240
|
+
for (const [key, value] of Object.entries(params.query))
|
|
241
|
+
url.searchParams.set(key, value);
|
|
242
|
+
}
|
|
243
|
+
const headers = new Headers(config.authStrategy.getHeaders());
|
|
244
|
+
headers.set("Accept", params.accept ?? "application/json");
|
|
245
|
+
if (params.body !== void 0)
|
|
246
|
+
headers.set("Content-Type", "application/json");
|
|
247
|
+
const response = await fetch(url, {
|
|
248
|
+
method: params.method,
|
|
249
|
+
headers,
|
|
250
|
+
body: params.body !== void 0 ? JSON.stringify(params.body) : void 0,
|
|
251
|
+
signal: params.signal
|
|
252
|
+
});
|
|
253
|
+
if (!response.ok)
|
|
254
|
+
throw await FetchError.from(url.toString(), params.method, response);
|
|
255
|
+
return response;
|
|
256
|
+
}
|
|
257
|
+
async function executeAgent(input) {
|
|
258
|
+
const body = executeAgentRequestSchema.parse(input);
|
|
259
|
+
const response = await request({
|
|
260
|
+
method: "POST",
|
|
261
|
+
path: "/v4/agents/execute",
|
|
262
|
+
body
|
|
263
|
+
});
|
|
264
|
+
return executeAgentResponseSchema.parse(await response.json());
|
|
265
|
+
}
|
|
266
|
+
async function streamSession(sessionId, options) {
|
|
267
|
+
const response = await request({
|
|
268
|
+
method: "GET",
|
|
269
|
+
path: `/v4/sessions/${encodeURIComponent(sessionId)}`,
|
|
270
|
+
query: options?.cursor !== void 0 ? { cursor: String(options.cursor) } : void 0,
|
|
271
|
+
accept: "text/event-stream, application/json",
|
|
272
|
+
signal: options?.signal
|
|
273
|
+
});
|
|
274
|
+
if (!response.body)
|
|
275
|
+
throw new Error("Agent session stream response body is missing");
|
|
276
|
+
return parseSessionStream(response.body);
|
|
277
|
+
}
|
|
278
|
+
async function resolveReference(reference, options) {
|
|
279
|
+
if (!config.vaultUrl)
|
|
280
|
+
throw new Error("vaultUrl is required in AgentClientConfig to resolve references");
|
|
281
|
+
if (!reference.startsWith("vault://"))
|
|
282
|
+
throw new Error(`Unsupported vault reference: ${reference}`);
|
|
283
|
+
const vaultConfig = { vaultUrl: config.vaultUrl, authStrategy: config.authStrategy };
|
|
284
|
+
const as = options?.as ?? "bytes";
|
|
285
|
+
if (as === "stream") {
|
|
286
|
+
const vaultFile2 = await VaultFile.fromVaultReference(
|
|
287
|
+
{ reference, config: vaultConfig, download: false },
|
|
288
|
+
{ signal: options?.signal }
|
|
289
|
+
);
|
|
290
|
+
return vaultFile2.downloadStream({ signal: options?.signal });
|
|
291
|
+
}
|
|
292
|
+
const vaultFile = await VaultFile.fromVaultReference(
|
|
293
|
+
{ reference, config: vaultConfig, download: true },
|
|
294
|
+
{ signal: options?.signal }
|
|
295
|
+
);
|
|
296
|
+
if (!vaultFile.content)
|
|
297
|
+
throw new Error(`Vault content missing for ${reference}`);
|
|
298
|
+
if (as === "json")
|
|
299
|
+
return JSON.parse(await vaultFile.content.text());
|
|
300
|
+
return vaultFile.content.arrayBuffer();
|
|
301
|
+
}
|
|
302
|
+
return { executeAgent, streamSession, resolveReference };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export { APIKeyAuthStrategy, DataTokenAuthStrategy, FetchError, agentClient, agentInputSchema, executeAgentRequestSchema, executeAgentResponseSchema, parseSessionStream, sessionStatusSchema, sessionStreamEventSchema };
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@meistrari/agent-sdk",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/meistrari/agent-api.git",
|
|
9
|
+
"directory": "packages/agent-sdk"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"bun": "./src/index.ts",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.mjs",
|
|
16
|
+
"require": "./dist/index.cjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"main": "dist/index.mjs",
|
|
20
|
+
"types": "dist/index.d.ts",
|
|
21
|
+
"files": [
|
|
22
|
+
"dist"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "unbuild",
|
|
26
|
+
"typecheck": "bunx tsc --noEmit",
|
|
27
|
+
"test:unit": "bun test test/",
|
|
28
|
+
"lint": "eslint ."
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"typescript": "^5.0.0"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@meistrari/vault-sdk": "1.9.0",
|
|
35
|
+
"zod": "4.1.12"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/bun": "latest",
|
|
39
|
+
"unbuild": "2.0.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
}
|
|
44
|
+
}
|