create-expert 0.0.40 → 0.0.41

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.
@@ -1,1706 +0,0 @@
1
- import { B as instructionMessageSchema, G as boolean$1, H as toolMessageSchema, K as number$1, L as usageSchema, Lt as PerstackError, Q as _undefined, R as toolResultSchema, U as userMessageSchema, V as messageSchema, W as activityOrGroupSchema, Y as _enum, Z as _null, _t as union, at as lazy, et as array, ft as preprocess, ht as string, lt as number, ot as literal, pt as record, rt as discriminatedUnion, tt as boolean, ut as object, vt as unknown, z as toolCallSchema } from "./src-Ct-kpNVU.js";
2
-
3
- //#region ../../node_modules/.pnpm/@perstack+api-client@0.0.56_@perstack+core@packages+core_zod@4.3.6/node_modules/@perstack/api-client/dist/index.mjs
4
- function createValidationError(error) {
5
- return {
6
- type: "validation",
7
- message: `Validation failed: ${error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`,
8
- reason: error.issues
9
- };
10
- }
11
- function validationErrorResult(error) {
12
- return {
13
- ok: false,
14
- status: 0,
15
- headers: new Headers(),
16
- error: createValidationError(error)
17
- };
18
- }
19
- function createAbortError() {
20
- return {
21
- type: "abort",
22
- message: "Request aborted"
23
- };
24
- }
25
- function createTimeoutError() {
26
- return {
27
- type: "timeout",
28
- message: "Request timed out"
29
- };
30
- }
31
- function createNetworkError(error) {
32
- return {
33
- type: "network",
34
- message: error instanceof Error ? error.message : "Network error",
35
- reason: error,
36
- cause: error instanceof Error ? error : void 0
37
- };
38
- }
39
- async function handleHttpError(response) {
40
- let errorBody;
41
- try {
42
- errorBody = await response.json();
43
- } catch {
44
- errorBody = void 0;
45
- }
46
- return {
47
- ok: false,
48
- status: response.status,
49
- headers: response.headers,
50
- error: createHttpError(response.statusText, errorBody)
51
- };
52
- }
53
- function createHttpError(statusText, body) {
54
- if (typeof body === "object" && body !== null) {
55
- const hasReason = "reason" in body;
56
- if ("error" in body && typeof body.error === "string") return {
57
- type: "http",
58
- message: body.error,
59
- reason: hasReason ? body.reason : void 0
60
- };
61
- if (hasReason) return {
62
- type: "http",
63
- message: statusText,
64
- reason: body.reason
65
- };
66
- }
67
- return {
68
- type: "http",
69
- message: statusText
70
- };
71
- }
72
- const DEFAULT_BASE_URL = "https://api.perstack.ai";
73
- const DEFAULT_TIMEOUT = 6e4;
74
- function createFetcher(config) {
75
- const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
76
- const timeout = config.timeout ?? DEFAULT_TIMEOUT;
77
- const useCredentials = config.credentials === "include";
78
- const apiKey = config.apiKey;
79
- function buildUrl(path) {
80
- return `${baseUrl}${path}`;
81
- }
82
- function buildHeaders(options) {
83
- const headers = {};
84
- if (options?.hasBody) headers["Content-Type"] = "application/json";
85
- if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
86
- return headers;
87
- }
88
- function getCredentials() {
89
- return useCredentials ? "include" : void 0;
90
- }
91
- function createTimeoutSignal(externalSignal) {
92
- const controller = new AbortController();
93
- let timedOut = false;
94
- const timeoutId = setTimeout(() => {
95
- timedOut = true;
96
- controller.abort();
97
- }, timeout);
98
- let abortHandler;
99
- if (externalSignal) if (externalSignal.aborted) controller.abort();
100
- else {
101
- abortHandler = () => controller.abort();
102
- externalSignal.addEventListener("abort", abortHandler);
103
- }
104
- return {
105
- signal: controller.signal,
106
- cleanup: () => {
107
- clearTimeout(timeoutId);
108
- if (abortHandler && externalSignal) externalSignal.removeEventListener("abort", abortHandler);
109
- },
110
- isTimeout: () => timedOut
111
- };
112
- }
113
- function wrapStreamWithIdleTimeout(stream, idleTimeoutMs, externalSignal) {
114
- const reader = stream.getReader();
115
- const controller = new AbortController();
116
- let timeoutId;
117
- let abortHandler;
118
- if (externalSignal) if (externalSignal.aborted) controller.abort();
119
- else {
120
- abortHandler = () => controller.abort();
121
- externalSignal.addEventListener("abort", abortHandler);
122
- }
123
- function resetTimeout() {
124
- if (timeoutId) clearTimeout(timeoutId);
125
- timeoutId = setTimeout(() => controller.abort(), idleTimeoutMs);
126
- }
127
- function cleanup() {
128
- if (timeoutId) clearTimeout(timeoutId);
129
- if (abortHandler && externalSignal) externalSignal.removeEventListener("abort", abortHandler);
130
- }
131
- return new ReadableStream({
132
- start() {
133
- resetTimeout();
134
- },
135
- async pull(streamController) {
136
- try {
137
- const result = await Promise.race([reader.read(), new Promise((_, reject) => {
138
- if (controller.signal.aborted) reject(new DOMException("Stream idle timeout", "AbortError"));
139
- controller.signal.addEventListener("abort", () => {
140
- reject(new DOMException("Stream idle timeout", "AbortError"));
141
- });
142
- })]);
143
- if (result.done) {
144
- cleanup();
145
- streamController.close();
146
- return;
147
- }
148
- resetTimeout();
149
- streamController.enqueue(result.value);
150
- } catch (error) {
151
- cleanup();
152
- reader.cancel().catch(() => {});
153
- if (error instanceof DOMException && error.name === "AbortError") streamController.error(new DOMException("Stream idle timeout", "AbortError"));
154
- else streamController.error(error);
155
- }
156
- },
157
- cancel(reason) {
158
- cleanup();
159
- reader.cancel(reason).catch(() => {});
160
- }
161
- });
162
- }
163
- async function request(method, path, body, options) {
164
- const { signal, cleanup, isTimeout } = createTimeoutSignal(options?.signal);
165
- try {
166
- const response = await fetch(buildUrl(path), {
167
- method,
168
- headers: buildHeaders(body ? { hasBody: true } : void 0),
169
- body: body ? JSON.stringify(body) : void 0,
170
- signal,
171
- credentials: getCredentials()
172
- });
173
- if (!response.ok) return handleHttpError(response);
174
- const json = await response.json();
175
- return {
176
- ok: true,
177
- status: response.status,
178
- headers: response.headers,
179
- data: json
180
- };
181
- } catch (error) {
182
- if (error instanceof Error && error.name === "AbortError") {
183
- if (isTimeout()) return {
184
- ok: false,
185
- status: 0,
186
- headers: new Headers(),
187
- error: createTimeoutError()
188
- };
189
- return {
190
- ok: false,
191
- status: 0,
192
- headers: new Headers(),
193
- error: createAbortError()
194
- };
195
- }
196
- return {
197
- ok: false,
198
- status: 0,
199
- headers: new Headers(),
200
- error: createNetworkError(error)
201
- };
202
- } finally {
203
- cleanup();
204
- }
205
- }
206
- async function requestBlob(path, options) {
207
- const { signal, cleanup, isTimeout } = createTimeoutSignal(options?.signal);
208
- try {
209
- const response = await fetch(buildUrl(path), {
210
- method: "GET",
211
- headers: buildHeaders(),
212
- signal,
213
- credentials: getCredentials()
214
- });
215
- if (!response.ok) return handleHttpError(response);
216
- const blob = await response.blob();
217
- return {
218
- ok: true,
219
- status: response.status,
220
- headers: response.headers,
221
- data: blob
222
- };
223
- } catch (error) {
224
- if (error instanceof Error && error.name === "AbortError") {
225
- if (isTimeout()) return {
226
- ok: false,
227
- status: 0,
228
- headers: new Headers(),
229
- error: createTimeoutError()
230
- };
231
- return {
232
- ok: false,
233
- status: 0,
234
- headers: new Headers(),
235
- error: createAbortError()
236
- };
237
- }
238
- return {
239
- ok: false,
240
- status: 0,
241
- headers: new Headers(),
242
- error: createNetworkError(error)
243
- };
244
- } finally {
245
- cleanup();
246
- }
247
- }
248
- async function requestStream(path, options) {
249
- const { signal, cleanup, isTimeout } = createTimeoutSignal(options?.signal);
250
- try {
251
- const response = await fetch(buildUrl(path), {
252
- method: "GET",
253
- headers: buildHeaders(),
254
- signal,
255
- credentials: getCredentials()
256
- });
257
- if (!response.ok) {
258
- cleanup();
259
- return handleHttpError(response);
260
- }
261
- if (!response.body) {
262
- cleanup();
263
- return {
264
- ok: false,
265
- status: response.status,
266
- headers: response.headers,
267
- error: createNetworkError(/* @__PURE__ */ new Error("Response body is null"))
268
- };
269
- }
270
- cleanup();
271
- const idleTimeout = options?.streamIdleTimeout ?? timeout;
272
- const wrappedStream = wrapStreamWithIdleTimeout(response.body, idleTimeout, options?.signal);
273
- return {
274
- ok: true,
275
- status: response.status,
276
- headers: response.headers,
277
- data: wrappedStream
278
- };
279
- } catch (error) {
280
- cleanup();
281
- if (error instanceof Error && error.name === "AbortError") {
282
- if (isTimeout()) return {
283
- ok: false,
284
- status: 0,
285
- headers: new Headers(),
286
- error: createTimeoutError()
287
- };
288
- return {
289
- ok: false,
290
- status: 0,
291
- headers: new Headers(),
292
- error: createAbortError()
293
- };
294
- }
295
- return {
296
- ok: false,
297
- status: 0,
298
- headers: new Headers(),
299
- error: createNetworkError(error)
300
- };
301
- }
302
- }
303
- async function requestNoContent(method, path, options) {
304
- const { signal, cleanup, isTimeout } = createTimeoutSignal(options?.signal);
305
- try {
306
- const response = await fetch(buildUrl(path), {
307
- method,
308
- headers: buildHeaders(),
309
- signal,
310
- credentials: getCredentials()
311
- });
312
- if (!response.ok) return handleHttpError(response);
313
- return {
314
- ok: true,
315
- status: response.status,
316
- headers: response.headers,
317
- data: void 0
318
- };
319
- } catch (error) {
320
- if (error instanceof Error && error.name === "AbortError") {
321
- if (isTimeout()) return {
322
- ok: false,
323
- status: 0,
324
- headers: new Headers(),
325
- error: createTimeoutError()
326
- };
327
- return {
328
- ok: false,
329
- status: 0,
330
- headers: new Headers(),
331
- error: createAbortError()
332
- };
333
- }
334
- return {
335
- ok: false,
336
- status: 0,
337
- headers: new Headers(),
338
- error: createNetworkError(error)
339
- };
340
- } finally {
341
- cleanup();
342
- }
343
- }
344
- return {
345
- get: (path, options) => request("GET", path, void 0, options),
346
- post: (path, body, options) => request("POST", path, body, options),
347
- put: (path, body, options) => request("PUT", path, body, options),
348
- delete: (path, options) => request("DELETE", path, void 0, options),
349
- deleteNoContent: (path, options) => requestNoContent("DELETE", path, options),
350
- getBlob: (path, options) => requestBlob(path, options),
351
- getStream: (path, options) => requestStream(path, options)
352
- };
353
- }
354
- function buildQueryString(params) {
355
- if (!params) return "";
356
- const searchParams = new URLSearchParams();
357
- for (const [key, value] of Object.entries(params)) if (value !== void 0) searchParams.set(key, String(value));
358
- const queryString = searchParams.toString();
359
- return queryString ? `?${queryString}` : "";
360
- }
361
- async function* parseSSEEvents(reader) {
362
- const decoder = new TextDecoder();
363
- let buffer = "";
364
- while (true) {
365
- const { value, done } = await reader.read();
366
- if (done) break;
367
- buffer += decoder.decode(value, { stream: true });
368
- const events = buffer.split("\n\n");
369
- buffer = events.pop() || "";
370
- for (const event of events) {
371
- if (event.trim() === "") continue;
372
- const lines = event.split("\n");
373
- const eventType = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
374
- const data = lines.find((line) => line.startsWith("data:"))?.slice(5).trim();
375
- if (!eventType || !data) continue;
376
- if (eventType !== "message" && eventType !== "error" && eventType !== "complete") continue;
377
- try {
378
- yield {
379
- event: eventType,
380
- data: JSON.parse(data)
381
- };
382
- } catch {}
383
- }
384
- }
385
- }
386
- const organizationNameRegex = /^[a-z0-9][a-z0-9_.-]*$/;
387
- const maxOrganizationNameLength = 128;
388
- const applicationNameRegex = /^[a-z0-9][a-z0-9_.-]*$/;
389
- const maxApplicationNameLength = 255;
390
- const maxVariableValueLength = 65536;
391
- const maxSecretValueLength = 65536;
392
- const expertKeyRegex = /^((?:@[a-z0-9][a-z0-9_.-]*\/)?[a-z0-9][a-z0-9_.-]*)(?:@((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?)|@([a-z0-9][a-z0-9_.-]*))?$/;
393
- const expertNameRegex = /^(@[a-z0-9][a-z0-9_-]*\/)?[a-z0-9][a-z0-9_-]*$/;
394
- const scopeNameRegex = /^[a-z0-9][a-z0-9_-]*$/;
395
- const scopeNameRefRegex = /^[a-z0-9][a-z0-9_-]*(?:@(?:(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?|[a-z0-9][a-z0-9_-]*))?$/;
396
- const expertVersionRegex = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/;
397
- const tagNameRegex = /^[a-z0-9][a-z0-9_-]*$/;
398
- const maxExpertNameLength = 255;
399
- const maxExpertVersionTagLength = 255;
400
- const maxExpertKeyLength = 511;
401
- const maxExpertDescriptionLength = 1024 * 2;
402
- const maxExpertInstructionLength = 1024 * 20;
403
- const maxExpertDelegateItems = 255;
404
- const maxExpertTagItems = 8;
405
- const maxExpertJobQueryLength = 1024 * 20;
406
- const packageWithVersionRegex = /^(?:@[a-z0-9][a-z0-9_.-]*\/)?[a-z0-9][a-z0-9_.-]*(?:@(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?|@[a-z0-9][a-z0-9_.-]*)?$/;
407
- const urlSafeRegex = /^[a-z0-9][a-z0-9_-]*$/;
408
- const maxSkillNameLength = 255;
409
- const maxSkillDescriptionLength = 1024 * 2;
410
- const maxSkillRuleLength = 1024 * 2;
411
- const maxSkillPickOmitItems = 255;
412
- const maxSkillRequiredEnvItems = 255;
413
- const maxSkillToolNameLength = 255;
414
- const maxSkillEndpointLength = 1024 * 2;
415
- const maxSkillInputJsonSchemaLength = 1024 * 20;
416
- const maxCheckpointToolCallIdLength = 255;
417
- const envNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
418
- const maxEnvNameLength = 255;
419
- const maxProviderBaseUrlLength = 2048;
420
- const maxProviderHeaderKeyLength = 255;
421
- const maxProviderHeaderValueLength = 2048;
422
- const maxProviderHeadersCount = 50;
423
- const cuidSchema = string().cuid2();
424
- string().min(24).cuid2();
425
- const runtimeVersionSchema = _enum(["v1.0"]);
426
- const providerSchema = _enum([
427
- "anthropic",
428
- "google",
429
- "openai",
430
- "deepseek",
431
- "azure-openai",
432
- "amazon-bedrock",
433
- "google-vertex"
434
- ]);
435
- const datetimeSchema = string().datetime({ offset: true });
436
- const expertKeyFieldSchema = string().min(1).max(maxExpertKeyLength).regex(expertKeyRegex);
437
- const expertNameFieldSchema = string().min(1).max(maxExpertNameLength).regex(expertNameRegex);
438
- const expertVersionFieldSchema = string().min(1).max(maxExpertVersionTagLength).regex(expertVersionRegex);
439
- const expertTagFieldSchema = string().min(1).max(maxExpertVersionTagLength).regex(tagNameRegex);
440
- const expertCategoryFieldSchema = _enum([
441
- "general",
442
- "coding",
443
- "research",
444
- "writing",
445
- "data",
446
- "automation"
447
- ]);
448
- const scopeNameSchema = string().min(1).max(maxExpertNameLength).regex(scopeNameRegex);
449
- string().min(1).max(maxExpertNameLength + maxExpertVersionTagLength + 1).regex(scopeNameRefRegex);
450
- string().min(1).max(30);
451
- const organizationStatusSchema = _enum([
452
- "active",
453
- "inactive",
454
- "deleted"
455
- ]);
456
- const organizationTypeSchema = _enum([
457
- "personal",
458
- "personalPlus",
459
- "team",
460
- "serviceAdmin"
461
- ]);
462
- const organizationSchema = object({
463
- type: literal("organization"),
464
- id: cuidSchema,
465
- createdAt: datetimeSchema,
466
- updatedAt: datetimeSchema,
467
- name: string().min(1).max(maxOrganizationNameLength).regex(organizationNameRegex).optional(),
468
- nameChangedAt: datetimeSchema.optional(),
469
- status: organizationStatusSchema,
470
- organizationType: organizationTypeSchema,
471
- maxApplications: number().int().min(0),
472
- maxApiKeys: number().int().min(0),
473
- maxExperts: number().int().min(0)
474
- });
475
- /**
476
- * Dedent function for multi-line template strings.
477
- * Adapted from ts-dedent (MIT License) to provide pure ESM support.
478
- *
479
- * Removes leading indentation from multi-line strings while preserving
480
- * relative indentation between lines.
481
- */
482
- function dedent(templ, ...values) {
483
- let strings = Array.from(typeof templ === "string" ? [templ] : templ);
484
- const lastIndex = strings.length - 1;
485
- strings[lastIndex] = (strings[lastIndex] ?? "").replace(/\r?\n([\t ]*)$/, "");
486
- const indentLengths = strings.reduce((arr, str) => {
487
- const matches = str.match(/\n([\t ]+|(?!\s).)/g);
488
- if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
489
- return arr;
490
- }, []);
491
- if (indentLengths.length) {
492
- const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, "g");
493
- strings = strings.map((str) => str.replace(pattern, "\n"));
494
- }
495
- strings[0] = (strings[0] ?? "").replace(/^\r?\n/, "");
496
- let string = strings[0] ?? "";
497
- values.forEach((value, i) => {
498
- const endentation = string.match(/(?:^|\n)( *)$/)?.[1] ?? "";
499
- let indentedValue = value;
500
- if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, j) => {
501
- return j === 0 ? str : `${endentation}${str}`;
502
- }).join("\n");
503
- string += String(indentedValue) + (strings[i + 1] ?? "");
504
- });
505
- return string;
506
- }
507
- object({
508
- code: literal(400),
509
- error: literal("Bad Request"),
510
- reason: string()
511
- }).describe("Bad Request");
512
- object({
513
- code: literal(401),
514
- error: literal("Unauthorized"),
515
- reason: literal("Failed to authenticate")
516
- }).describe(dedent`
517
- Authentication failed. Possible reasons:
518
- - Authorization header is not provided
519
- - Invalid API key
520
- - Session expired
521
- `);
522
- object({
523
- code: literal(403),
524
- error: literal("Forbidden"),
525
- reason: string()
526
- }).describe("Access denied. The authenticated user does not have permission to perform this action.");
527
- object({
528
- code: literal(403),
529
- error: literal("Forbidden"),
530
- reason: string(),
531
- details: object({
532
- minutesUsed: number(),
533
- limitMinutes: number(),
534
- upgradeUrl: string()
535
- })
536
- }).describe("Usage limit exceeded. Upgrade your plan to continue.");
537
- object({
538
- code: literal(404),
539
- error: literal("Not Found"),
540
- reason: string()
541
- }).describe("Resource not found.");
542
- object({
543
- code: literal(409),
544
- error: literal("Conflict"),
545
- reason: string()
546
- }).describe("Request conflicts with current state of the resource.");
547
- object({
548
- code: literal(503),
549
- error: literal("Service Unavailable"),
550
- reason: string()
551
- }).describe("Service temporarily unavailable. Retry with exponential backoff.");
552
- object({
553
- code: literal(422),
554
- error: literal("Validation Failed"),
555
- reason: unknown()
556
- }).describe("Request validation failed. Check the request body, query parameters, or path parameters.");
557
- const paginationMeta = object({
558
- total: number().int().min(0),
559
- take: number().int().min(1),
560
- skip: number().int().min(0)
561
- });
562
- object({
563
- code: literal(401),
564
- error: literal("Unauthorized"),
565
- reason: string()
566
- }).describe("Unauthorized");
567
- const applicationNameSchema = string().min(1).max(maxApplicationNameLength).regex(applicationNameRegex);
568
- const applicationStatusSchema = _enum([
569
- "active",
570
- "inactive",
571
- "deleted"
572
- ]);
573
- const applicationSchema = object({
574
- type: literal("application"),
575
- id: cuidSchema,
576
- organizationId: cuidSchema,
577
- organization: organizationSchema,
578
- createdAt: datetimeSchema,
579
- updatedAt: datetimeSchema,
580
- name: applicationNameSchema,
581
- status: applicationStatusSchema,
582
- expertCount: number().describe("Number of expert draft scopes associated with this application").optional(),
583
- providers: array(providerSchema).describe("List of configured providers for this application").optional(),
584
- totalJobs: number().describe("Total number of jobs executed for this application").optional(),
585
- lastJobExecutionAt: string().datetime({ offset: true }).nullable().describe("Timestamp of the most recent job execution").optional()
586
- });
587
- const request$21 = { body: object({
588
- name: applicationNameSchema,
589
- applicationGroupId: cuidSchema.optional()
590
- }) };
591
- object({ data: object({ application: applicationSchema }) });
592
- const request$20 = { query: object({
593
- name: preprocess((val) => Array.isArray(val) ? val.join(",") : val, string().optional()),
594
- sort: _enum([
595
- "name",
596
- "createdAt",
597
- "updatedAt"
598
- ]).optional(),
599
- order: _enum(["asc", "desc"]).optional(),
600
- take: number$1().min(1).max(100).default(20),
601
- skip: number$1().min(0).default(0)
602
- }) };
603
- object({
604
- data: object({ applications: array(applicationSchema) }),
605
- meta: paginationMeta
606
- });
607
- const request$19 = {
608
- params: object({ applicationId: cuidSchema }),
609
- body: object({
610
- name: applicationNameSchema.optional(),
611
- status: applicationStatusSchema.exclude(["deleted"]).optional()
612
- }).refine((data) => data.name !== void 0 || data.status !== void 0, { message: "At least one field must be provided" })
613
- };
614
- object({ data: object({ application: applicationSchema }) });
615
- const secretNameSchema = string().min(1, "Secret name is required").max(255, "Secret name must be 255 characters or less").regex(/^[A-Z][A-Z0-9_]*$/, "Secret name must start with uppercase letter and contain only uppercase letters, numbers, and underscores");
616
- const secretValueSchema = string().min(1, "Secret value is required").max(maxSecretValueLength);
617
- const secretMetadataSchema = object({
618
- name: string(),
619
- createdAt: datetimeSchema,
620
- updatedAt: datetimeSchema
621
- });
622
- object({
623
- type: literal("secret"),
624
- id: cuidSchema,
625
- name: secretNameSchema,
626
- applicationId: cuidSchema,
627
- createdAt: datetimeSchema,
628
- updatedAt: datetimeSchema
629
- });
630
- const request$18 = { body: object({
631
- applicationId: cuidSchema,
632
- name: secretNameSchema,
633
- value: secretValueSchema
634
- }) };
635
- object({ data: object({ secret: secretMetadataSchema }) });
636
- const request$17 = {
637
- params: object({ name: string().min(1) }),
638
- query: object({ applicationId: cuidSchema })
639
- };
640
- _null();
641
- const request$16 = {
642
- params: object({ name: string().min(1) }),
643
- query: object({ applicationId: cuidSchema })
644
- };
645
- object({ data: object({ secret: secretMetadataSchema }) });
646
- const request$15 = { query: object({ applicationId: cuidSchema.optional() }) };
647
- object({ data: object({ secrets: array(secretMetadataSchema) }) });
648
- const request$14 = {
649
- params: object({ name: string().min(1) }),
650
- body: object({
651
- applicationId: cuidSchema,
652
- value: secretValueSchema
653
- })
654
- };
655
- object({ data: object({ secret: secretMetadataSchema }) });
656
- const variableNameSchema = string().min(1).max(255).regex(/^[A-Z][A-Z0-9_]*$/, "Variable name must start with uppercase letter and contain only uppercase letters, digits, and underscores");
657
- const variableValueSchema = string().max(maxVariableValueLength);
658
- object({
659
- type: literal("variable"),
660
- id: cuidSchema,
661
- applicationId: cuidSchema,
662
- createdAt: datetimeSchema,
663
- updatedAt: datetimeSchema,
664
- name: variableNameSchema,
665
- value: variableValueSchema
666
- });
667
- const variableResponseSchema = object({
668
- name: variableNameSchema,
669
- value: variableValueSchema,
670
- createdAt: datetimeSchema,
671
- updatedAt: datetimeSchema
672
- });
673
- const request$13 = { body: object({
674
- applicationId: cuidSchema,
675
- name: variableNameSchema,
676
- value: variableValueSchema
677
- }) };
678
- object({ data: object({ variable: variableResponseSchema }) });
679
- const request$12 = {
680
- params: object({ name: string().min(1) }),
681
- query: object({ applicationId: cuidSchema })
682
- };
683
- _null();
684
- const request$11 = {
685
- params: object({ name: string().min(1) }),
686
- query: object({ applicationId: cuidSchema })
687
- };
688
- object({ data: object({ variable: variableResponseSchema }) });
689
- const request$10 = { query: object({ applicationId: cuidSchema }) };
690
- object({ data: object({ variables: array(variableResponseSchema) }) });
691
- const request$9 = {
692
- params: object({ name: string().min(1) }),
693
- body: object({
694
- applicationId: cuidSchema,
695
- value: variableValueSchema
696
- })
697
- };
698
- object({ data: object({ variable: variableResponseSchema }) });
699
- const expertScopeSchema = object({
700
- id: cuidSchema,
701
- name: scopeNameSchema,
702
- organizationId: cuidSchema,
703
- expertDraftScopeId: cuidSchema,
704
- published: boolean(),
705
- publishedAt: datetimeSchema.nullable(),
706
- category: expertCategoryFieldSchema,
707
- totalRuns: number().int().min(0),
708
- totalJobs: number().int().min(0),
709
- totalStars: number().int().min(0),
710
- createdAt: datetimeSchema,
711
- updatedAt: datetimeSchema,
712
- createdBy: cuidSchema,
713
- updatedBy: cuidSchema
714
- });
715
- const expertVersionSchema = object({
716
- id: cuidSchema,
717
- expertScopeId: cuidSchema,
718
- version: expertVersionFieldSchema,
719
- public: boolean(),
720
- yanked: boolean(),
721
- totalRuns: number().int().min(0),
722
- totalJobs: number().int().min(0),
723
- createdAt: datetimeSchema,
724
- updatedAt: datetimeSchema,
725
- createdBy: cuidSchema,
726
- updatedBy: cuidSchema,
727
- tags: array(expertTagFieldSchema),
728
- readmeUrl: string().optional()
729
- });
730
- expertScopeSchema.extend({ versions: array(expertVersionSchema) });
731
- function isPrivateOrLocalIP(hostname) {
732
- if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "0.0.0.0") return true;
733
- const ipv4Match = hostname.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
734
- if (ipv4Match) {
735
- const a = Number(ipv4Match[1]);
736
- const b = Number(ipv4Match[2]);
737
- if (a === 10) return true;
738
- if (a === 172 && b >= 16 && b <= 31) return true;
739
- if (a === 192 && b === 168) return true;
740
- if (a === 169 && b === 254) return true;
741
- if (a === 127) return true;
742
- }
743
- if (hostname.includes(":")) {
744
- if (hostname.startsWith("fe80:") || hostname.startsWith("fc") || hostname.startsWith("fd")) return true;
745
- }
746
- if (hostname.startsWith("::ffff:")) {
747
- if (isPrivateOrLocalIP(hostname.slice(7))) return true;
748
- }
749
- return false;
750
- }
751
- const sseEndpointSchema = string().max(maxSkillEndpointLength).url().refine((url) => {
752
- try {
753
- const parsed = new URL(url);
754
- if (parsed.protocol !== "https:") return false;
755
- if (isPrivateOrLocalIP(parsed.hostname)) return false;
756
- return true;
757
- } catch {
758
- return false;
759
- }
760
- }, { message: "Endpoint must be a public HTTPS URL" });
761
- const skillNameSchema = string().min(1).max(maxSkillNameLength).regex(packageWithVersionRegex);
762
- const mcpStdioSkillCommandSchema = _enum(["npx", "uvx"]);
763
- const mcpStdioSkillSchema = object({
764
- type: literal("mcpStdioSkill"),
765
- name: string().min(1),
766
- description: string().min(1).max(maxSkillDescriptionLength),
767
- rule: string().min(1).max(maxSkillRuleLength).optional(),
768
- pick: array(string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
769
- omit: array(string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
770
- command: mcpStdioSkillCommandSchema,
771
- packageName: string().min(1).max(maxSkillNameLength).regex(packageWithVersionRegex),
772
- requiredEnv: array(string().min(1).max(maxEnvNameLength).regex(envNameRegex)).max(maxSkillRequiredEnvItems).optional().default([])
773
- });
774
- const mcpSseSkillSchema = object({
775
- type: literal("mcpSseSkill"),
776
- name: string().min(1),
777
- description: string().min(1).max(maxSkillDescriptionLength),
778
- rule: string().min(1).max(maxSkillRuleLength).optional(),
779
- pick: array(string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
780
- omit: array(string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
781
- endpoint: sseEndpointSchema
782
- });
783
- const interactiveSkillSchema = object({
784
- type: literal("interactiveSkill"),
785
- name: string().min(1),
786
- description: string().min(1).max(maxSkillDescriptionLength),
787
- rule: string().min(1).max(maxSkillRuleLength).optional(),
788
- tools: record(string().min(1).max(maxSkillToolNameLength).regex(urlSafeRegex), object({
789
- description: string().min(1).max(maxSkillDescriptionLength),
790
- inputJsonSchema: string().min(1).max(maxSkillInputJsonSchemaLength)
791
- }))
792
- });
793
- const skillSchema = discriminatedUnion("type", [
794
- mcpStdioSkillSchema,
795
- mcpSseSkillSchema,
796
- interactiveSkillSchema
797
- ]);
798
- const expertSchema = object({
799
- key: expertKeyFieldSchema,
800
- name: expertNameFieldSchema,
801
- version: expertVersionFieldSchema,
802
- description: string().max(maxExpertDescriptionLength).optional(),
803
- instruction: string().min(1).max(maxExpertInstructionLength),
804
- skills: record(skillNameSchema, skillSchema).optional().default({}),
805
- delegates: array(expertKeyFieldSchema).min(0).max(maxExpertDelegateItems).optional().default([]),
806
- tags: array(expertTagFieldSchema).min(0).max(maxExpertTagItems).optional().default([]),
807
- minRuntimeVersion: runtimeVersionSchema.optional().default("v1.0")
808
- });
809
- object({
810
- scope: expertScopeSchema,
811
- version: expertVersionSchema
812
- });
813
- const expertWithMetadataSchema = expertSchema.extend({
814
- scope: expertScopeSchema,
815
- version: expertVersionSchema
816
- });
817
- const request$8 = { query: object({
818
- filter: string().describe("Filter by scope name (partial match)").optional(),
819
- category: expertCategoryFieldSchema.describe("Filter by category").optional(),
820
- includeDrafts: boolean$1().default(false).describe("Include unpublished scopes (owner only)").optional(),
821
- take: number$1().min(1).max(100).default(20),
822
- skip: number$1().min(0).default(0)
823
- }) };
824
- object({
825
- data: object({ experts: array(expertScopeSchema.extend({ currentVersion: expertVersionSchema.nullable() })) }),
826
- meta: paginationMeta
827
- });
828
- const anthropicSupportModels = [
829
- {
830
- modelId: "claude-opus-4-6",
831
- default: false,
832
- provider: "anthropic",
833
- contextWindow: 2e5
834
- },
835
- {
836
- modelId: "claude-opus-4-5",
837
- default: false,
838
- provider: "anthropic",
839
- contextWindow: 2e5
840
- },
841
- {
842
- modelId: "claude-opus-4-1",
843
- default: false,
844
- provider: "anthropic",
845
- contextWindow: 2e5
846
- },
847
- {
848
- modelId: "claude-opus-4-20250514",
849
- default: false,
850
- provider: "anthropic",
851
- contextWindow: 2e5
852
- },
853
- {
854
- modelId: "claude-sonnet-4-5",
855
- default: true,
856
- provider: "anthropic",
857
- contextWindow: 2e5
858
- },
859
- {
860
- modelId: "claude-sonnet-4-20250514",
861
- default: false,
862
- provider: "anthropic",
863
- contextWindow: 2e5
864
- },
865
- {
866
- modelId: "claude-3-7-sonnet-20250219",
867
- default: false,
868
- provider: "anthropic",
869
- contextWindow: 2e5
870
- },
871
- {
872
- modelId: "claude-haiku-4-5",
873
- default: false,
874
- provider: "anthropic",
875
- contextWindow: 2e5
876
- },
877
- {
878
- modelId: "claude-3-5-haiku-latest",
879
- default: false,
880
- provider: "anthropic",
881
- contextWindow: 2e5
882
- }
883
- ];
884
- const googleSupportModels = [
885
- {
886
- modelId: "gemini-3-pro-preview",
887
- default: false,
888
- provider: "google",
889
- contextWindow: 1e6
890
- },
891
- {
892
- modelId: "gemini-2.5-pro",
893
- default: true,
894
- provider: "google",
895
- contextWindow: 1e6
896
- },
897
- {
898
- modelId: "gemini-2.5-flash",
899
- default: false,
900
- provider: "google",
901
- contextWindow: 1e6
902
- },
903
- {
904
- modelId: "gemini-2.5-flash-lite",
905
- default: false,
906
- provider: "google",
907
- contextWindow: 1e6
908
- },
909
- {
910
- modelId: "gemini-3-flash-preview",
911
- default: false,
912
- provider: "google",
913
- contextWindow: 1e6
914
- }
915
- ];
916
- const openAiSupportModels = [
917
- {
918
- modelId: "gpt-5",
919
- default: true,
920
- provider: "openai",
921
- contextWindow: 4e5
922
- },
923
- {
924
- modelId: "gpt-5-mini",
925
- default: false,
926
- provider: "openai",
927
- contextWindow: 4e5
928
- },
929
- {
930
- modelId: "gpt-5-nano",
931
- default: false,
932
- provider: "openai",
933
- contextWindow: 4e5
934
- },
935
- {
936
- modelId: "gpt-5-chat-latest",
937
- default: false,
938
- provider: "openai",
939
- contextWindow: 128e3
940
- },
941
- {
942
- modelId: "o4-mini",
943
- default: false,
944
- provider: "openai",
945
- contextWindow: 2e5
946
- },
947
- {
948
- modelId: "o3",
949
- default: false,
950
- provider: "openai",
951
- contextWindow: 2e5
952
- },
953
- {
954
- modelId: "o3-mini",
955
- default: false,
956
- provider: "openai",
957
- contextWindow: 2e5
958
- },
959
- {
960
- modelId: "gpt-4.1",
961
- default: false,
962
- provider: "openai",
963
- contextWindow: 1e6
964
- },
965
- {
966
- modelId: "gpt-5.1",
967
- default: false,
968
- provider: "openai",
969
- contextWindow: 4e5
970
- },
971
- {
972
- modelId: "gpt-5.2",
973
- default: false,
974
- provider: "openai",
975
- contextWindow: 4e5
976
- },
977
- {
978
- modelId: "gpt-5.2-pro",
979
- default: false,
980
- provider: "openai",
981
- contextWindow: 4e5
982
- }
983
- ];
984
- const deepseekSupportModels = [{
985
- modelId: "deepseek-chat",
986
- default: true,
987
- provider: "deepseek",
988
- contextWindow: 128e3
989
- }, {
990
- modelId: "deepseek-reasoner",
991
- default: false,
992
- provider: "deepseek",
993
- contextWindow: 128e3
994
- }];
995
- const allSupportModels = [
996
- ...anthropicSupportModels,
997
- ...googleSupportModels,
998
- ...openAiSupportModels,
999
- ...deepseekSupportModels
1000
- ];
1001
- const supportModels = Object.fromEntries(allSupportModels.map((model) => [model.modelId, model]));
1002
- function getSupportModelNames() {
1003
- return Object.keys(supportModels);
1004
- }
1005
- const reasoningBudgetSchema = union([_enum([
1006
- "none",
1007
- "minimal",
1008
- "low",
1009
- "medium",
1010
- "high"
1011
- ]), number().int().min(0)]);
1012
- const jobStatusSchema = _enum([
1013
- "queued",
1014
- "processing",
1015
- "completed",
1016
- "requestInteractiveToolResult",
1017
- "requestDelegateResult",
1018
- "exceededMaxSteps",
1019
- "failed",
1020
- "canceling",
1021
- "canceled",
1022
- "expired"
1023
- ]);
1024
- const modelNames = getSupportModelNames();
1025
- const firstModel = modelNames[0];
1026
- if (firstModel === void 0) throw new Error("No support models available");
1027
- const jobModelSchema = _enum([firstModel, ...modelNames.slice(1)]);
1028
- const jobBaseSchema = object({
1029
- type: literal("job"),
1030
- id: cuidSchema,
1031
- organizationId: cuidSchema,
1032
- applicationId: cuidSchema,
1033
- createdAt: datetimeSchema,
1034
- updatedAt: datetimeSchema,
1035
- status: jobStatusSchema,
1036
- currentExecutionId: cuidSchema.optional(),
1037
- machineId: cuidSchema.nullable(),
1038
- coordinatorExpertKey: expertKeyFieldSchema,
1039
- query: string().min(1).max(maxExpertJobQueryLength).optional(),
1040
- expert: expertWithMetadataSchema,
1041
- provider: providerSchema,
1042
- model: jobModelSchema,
1043
- reasoningBudget: reasoningBudgetSchema,
1044
- runtimeVersion: runtimeVersionSchema,
1045
- maxSteps: number().int().min(1),
1046
- maxRetries: number().int().min(0),
1047
- currentStep: number().int().min(0),
1048
- totalSteps: number().int().min(0),
1049
- totalDuration: number().int().min(0),
1050
- usage: usageSchema,
1051
- lastActivity: activityOrGroupSchema.nullable().optional()
1052
- });
1053
- const publishedJobSchema = jobBaseSchema.extend({
1054
- expertVersionId: cuidSchema,
1055
- expertDraftRefId: _undefined()
1056
- });
1057
- const draftJobSchema = jobBaseSchema.extend({
1058
- expertVersionId: _undefined(),
1059
- expertDraftRefId: cuidSchema
1060
- });
1061
- const jobSchema = union([publishedJobSchema, draftJobSchema]);
1062
- const request$7 = {
1063
- params: object({ jobId: cuidSchema }),
1064
- body: object({
1065
- query: string().min(1).max(maxExpertJobQueryLength),
1066
- provider: providerSchema.optional(),
1067
- model: jobModelSchema.optional(),
1068
- reasoningBudget: reasoningBudgetSchema.optional(),
1069
- maxSteps: number$1().optional(),
1070
- maxRetries: number$1().optional()
1071
- })
1072
- };
1073
- object({ data: object({ job: jobSchema }) });
1074
- const request$6 = { body: object({
1075
- applicationId: cuidSchema.describe("Application ID to create the job in"),
1076
- query: string().min(1).max(maxExpertJobQueryLength),
1077
- provider: providerSchema,
1078
- model: jobModelSchema.optional(),
1079
- reasoningBudget: reasoningBudgetSchema.optional(),
1080
- maxSteps: number$1().optional(),
1081
- maxRetries: number$1().optional()
1082
- }).extend({
1083
- expertKey: expertKeyFieldSchema.optional(),
1084
- draftRefId: cuidSchema.describe("Draft ref ID to run the job with").optional()
1085
- }).refine((data) => {
1086
- const hasExpertKey = data.expertKey !== void 0;
1087
- const hasDraftRefId = data.draftRefId !== void 0;
1088
- return hasExpertKey && !hasDraftRefId || !hasExpertKey && hasDraftRefId;
1089
- }, { message: "Either expertKey or draftRefId must be provided, but not both" }) };
1090
- object({ data: object({ job: jobSchema }) });
1091
- const request$5 = { query: object({
1092
- sort: _enum(["createdAt", "updatedAt"]).optional(),
1093
- order: _enum(["asc", "desc"]).optional(),
1094
- take: number$1().min(1).max(100).default(20),
1095
- skip: number$1().min(0).default(0),
1096
- expertScopeId: cuidSchema.optional(),
1097
- expertDraftScopeId: cuidSchema.optional(),
1098
- applicationId: cuidSchema.optional(),
1099
- statuses: preprocess((val) => typeof val === "string" ? val.split(",") : val, array(jobStatusSchema)).optional(),
1100
- expertKeyFilter: string().max(100).optional()
1101
- }) };
1102
- object({
1103
- data: object({ jobs: array(jobSchema) }),
1104
- meta: paginationMeta
1105
- });
1106
- const delegationTargetSchema = object({
1107
- expert: expertSchema,
1108
- toolCallId: string().min(1).max(maxCheckpointToolCallIdLength),
1109
- toolName: string().min(1).max(maxSkillToolNameLength),
1110
- query: string().min(1)
1111
- });
1112
- /**
1113
- * API Checkpoint schema - extended checkpoint format for API responses.
1114
- * Includes additional fields computed from runtime checkpoint and step data:
1115
- * - activities: computed via getActivities() from @perstack/core
1116
- * - inputMessages, newMessages, toolCalls, toolResults: step-related data
1117
- * - expert: full Expert type (with instruction, skills, etc.)
1118
- * - startedAt/finishedAt: ISO string format (runtime uses Unix timestamps)
1119
- */
1120
- const apiCheckpointSchema = object({
1121
- type: literal("checkpoint"),
1122
- id: cuidSchema,
1123
- jobId: cuidSchema,
1124
- runId: cuidSchema,
1125
- activities: array(activityOrGroupSchema),
1126
- stepNumber: number().int().min(1),
1127
- status: _enum([
1128
- "init",
1129
- "proceeding",
1130
- "completed",
1131
- "stoppedByInteractiveTool",
1132
- "stoppedByDelegate",
1133
- "stoppedByExceededMaxSteps",
1134
- "stoppedByError",
1135
- "stoppedByCancellation"
1136
- ]),
1137
- expert: expertSchema,
1138
- delegateTo: array(delegationTargetSchema).optional(),
1139
- delegatedBy: object({
1140
- expert: expertSchema,
1141
- toolCallId: string().min(1).max(maxCheckpointToolCallIdLength),
1142
- toolName: string().min(1).max(maxSkillToolNameLength),
1143
- checkpointId: cuidSchema,
1144
- runId: cuidSchema
1145
- }).optional(),
1146
- inputMessages: array(union([
1147
- instructionMessageSchema,
1148
- userMessageSchema,
1149
- toolMessageSchema
1150
- ])).optional(),
1151
- messages: array(messageSchema),
1152
- newMessages: array(messageSchema),
1153
- toolCalls: array(toolCallSchema).optional(),
1154
- toolResults: array(toolResultSchema).optional(),
1155
- pendingToolCalls: array(toolCallSchema).optional(),
1156
- partialToolResults: array(toolResultSchema).optional(),
1157
- usage: usageSchema,
1158
- contextWindow: number().int().min(0).optional(),
1159
- contextWindowUsage: number().int().min(0).optional(),
1160
- error: object({
1161
- name: string().min(1),
1162
- message: string().min(1),
1163
- statusCode: number().int().min(100).max(599).optional(),
1164
- isRetryable: boolean()
1165
- }).optional(),
1166
- retryCount: number().int().min(0).optional(),
1167
- startedAt: datetimeSchema,
1168
- finishedAt: datetimeSchema.optional()
1169
- });
1170
- const request$4 = {
1171
- params: object({
1172
- jobId: cuidSchema,
1173
- runId: cuidSchema
1174
- }),
1175
- query: object({
1176
- filter: string().min(1).max(256).optional(),
1177
- sort: _enum(["createdAt", "updatedAt"]).optional(),
1178
- order: _enum(["asc", "desc"]).optional(),
1179
- take: number$1().min(1).max(100).default(20),
1180
- skip: number$1().min(0).default(0)
1181
- })
1182
- };
1183
- object({
1184
- data: object({ checkpoints: array(apiCheckpointSchema) }),
1185
- meta: paginationMeta
1186
- });
1187
- const runTreeNodeSchema = object({
1188
- type: literal("run"),
1189
- id: cuidSchema,
1190
- jobId: cuidSchema,
1191
- executionId: cuidSchema.optional(),
1192
- parentRunId: cuidSchema.optional(),
1193
- organizationId: cuidSchema,
1194
- createdAt: datetimeSchema,
1195
- updatedAt: datetimeSchema,
1196
- expertKey: expertKeyFieldSchema,
1197
- expert: expertWithMetadataSchema,
1198
- stepNumber: number().int().min(0),
1199
- usage: usageSchema
1200
- }).extend({
1201
- lastCheckpointId: cuidSchema.nullable(),
1202
- checkpointIds: array(cuidSchema),
1203
- childRuns: lazy(() => array(runTreeNodeSchema))
1204
- });
1205
- const request$3 = {
1206
- params: object({ jobId: cuidSchema }),
1207
- query: object({
1208
- sort: _enum(["createdAt", "updatedAt"]).optional(),
1209
- order: _enum(["asc", "desc"]).optional(),
1210
- take: number$1().min(1).max(100).default(20),
1211
- skip: number$1().min(0).default(0),
1212
- depth: number$1().int().min(0).max(10).default(0)
1213
- })
1214
- };
1215
- object({
1216
- data: object({ runs: array(runTreeNodeSchema) }),
1217
- meta: paginationMeta
1218
- });
1219
- const baseUrlSchema = string().url().max(maxProviderBaseUrlLength).optional();
1220
- const headersSchema = record(string().min(1).max(maxProviderHeaderKeyLength), string().max(maxProviderHeaderValueLength)).refine((headers) => Object.keys(headers).length <= maxProviderHeadersCount, { message: `Headers must have at most ${maxProviderHeadersCount} entries` }).optional();
1221
- const anthropicProviderSettingsSchema = object({
1222
- baseUrl: baseUrlSchema,
1223
- headers: headersSchema
1224
- });
1225
- const googleProviderSettingsSchema = object({
1226
- baseUrl: baseUrlSchema,
1227
- headers: headersSchema
1228
- });
1229
- const openaiProviderSettingsSchema = object({
1230
- baseUrl: baseUrlSchema,
1231
- headers: headersSchema,
1232
- organization: string().min(1).optional(),
1233
- project: string().min(1).optional(),
1234
- name: string().min(1).optional()
1235
- });
1236
- const deepseekProviderSettingsSchema = object({
1237
- baseUrl: baseUrlSchema,
1238
- headers: headersSchema
1239
- });
1240
- const azureOpenaiProviderSettingsSchema = object({
1241
- baseUrl: baseUrlSchema,
1242
- headers: headersSchema,
1243
- resourceName: string().min(1).optional(),
1244
- apiVersion: string().min(1).optional(),
1245
- useDeploymentBasedUrls: boolean().optional()
1246
- });
1247
- const amazonBedrockProviderSettingsSchema = object({ region: string().min(1).optional() });
1248
- const googleVertexProviderSettingsSchema = object({
1249
- baseUrl: baseUrlSchema,
1250
- headers: headersSchema,
1251
- project: string().min(1).optional(),
1252
- location: string().min(1).optional()
1253
- });
1254
- const providerSettingsSchema = union([
1255
- anthropicProviderSettingsSchema,
1256
- googleProviderSettingsSchema,
1257
- openaiProviderSettingsSchema,
1258
- deepseekProviderSettingsSchema,
1259
- azureOpenaiProviderSettingsSchema,
1260
- amazonBedrockProviderSettingsSchema,
1261
- googleVertexProviderSettingsSchema
1262
- ]);
1263
- object({
1264
- type: literal("providerSetting"),
1265
- id: cuidSchema,
1266
- applicationId: cuidSchema,
1267
- provider: providerSchema,
1268
- settings: providerSettingsSchema.optional(),
1269
- application: applicationSchema,
1270
- createdAt: datetimeSchema,
1271
- updatedAt: datetimeSchema
1272
- });
1273
- const providerSettingResponseSchema = object({
1274
- type: literal("providerSetting"),
1275
- id: cuidSchema,
1276
- provider: providerSchema,
1277
- settings: providerSettingsSchema.optional(),
1278
- createdAt: datetimeSchema,
1279
- updatedAt: datetimeSchema
1280
- });
1281
- const providerApiKeyMetadataSchema = object({
1282
- id: cuidSchema,
1283
- name: string(),
1284
- createdAt: datetimeSchema,
1285
- updatedAt: datetimeSchema,
1286
- lastUsedAt: datetimeSchema.nullable(),
1287
- expiresAt: datetimeSchema.nullable()
1288
- });
1289
- const request$2 = {
1290
- params: object({
1291
- applicationId: cuidSchema,
1292
- provider: providerSchema
1293
- }),
1294
- body: object({
1295
- name: string().min(1).max(255),
1296
- value: string().min(1)
1297
- })
1298
- };
1299
- object({ data: object({ apiKey: providerApiKeyMetadataSchema }) });
1300
- const request$1 = {
1301
- params: object({ applicationId: cuidSchema }),
1302
- body: object({
1303
- provider: providerSchema,
1304
- settings: providerSettingsSchema.optional()
1305
- })
1306
- };
1307
- object({ data: object({ providerSetting: providerSettingResponseSchema }) });
1308
- const request = {
1309
- params: object({
1310
- applicationId: cuidSchema,
1311
- provider: providerSchema
1312
- }),
1313
- body: object({ settings: providerSettingsSchema.optional() })
1314
- };
1315
- object({ data: object({ providerSetting: providerSettingResponseSchema }) });
1316
- function createRunCheckpointsApi(fetcher, basePath) {
1317
- return {
1318
- async list(jobId, runId, params, options) {
1319
- if (params) {
1320
- const result = request$4.query.safeParse(params);
1321
- if (!result.success) return validationErrorResult(result.error);
1322
- }
1323
- const queryString = buildQueryString(params);
1324
- return fetcher.get(`${basePath}/${jobId}/runs/${runId}/checkpoints${queryString}`, options);
1325
- },
1326
- async get(jobId, runId, checkpointId, options) {
1327
- return fetcher.get(`${basePath}/${jobId}/runs/${runId}/checkpoints/${checkpointId}`, options);
1328
- }
1329
- };
1330
- }
1331
- function createListFn(fetcher, basePath) {
1332
- return async function list(jobId, params, options) {
1333
- if (params) {
1334
- const result = request$3.query.safeParse(params);
1335
- if (!result.success) return validationErrorResult(result.error);
1336
- }
1337
- const queryString = buildQueryString(params);
1338
- return fetcher.get(`${basePath}/${jobId}/runs${queryString}`, options);
1339
- };
1340
- }
1341
- function createRunsApi(fetcher, basePath) {
1342
- return {
1343
- list: createListFn(fetcher, basePath),
1344
- async get(jobId, runId, options) {
1345
- return fetcher.get(`${basePath}/${jobId}/runs/${runId}`, options);
1346
- },
1347
- checkpoints: createRunCheckpointsApi(fetcher, basePath)
1348
- };
1349
- }
1350
- const BASE_PATH$6 = "/api/v1/jobs";
1351
- /**
1352
- * Error thrown when stream ends abnormally.
1353
- */
1354
- var StreamError = class extends Error {
1355
- constructor(type, jobId, message) {
1356
- super(message ?? `Stream error: ${type}`);
1357
- this.type = type;
1358
- this.jobId = jobId;
1359
- this.name = "StreamError";
1360
- }
1361
- };
1362
- /**
1363
- * Error thrown when stream connection or reading fails.
1364
- */
1365
- var StreamConnectionError = class extends Error {
1366
- constructor(message) {
1367
- super(message);
1368
- this.name = "StreamConnectionError";
1369
- }
1370
- };
1371
- function isErrorEventData(data) {
1372
- return typeof data === "object" && data !== null && "type" in data && typeof data.type === "string" && "jobId" in data && typeof data.jobId === "string";
1373
- }
1374
- function isCompleteEventData(data) {
1375
- return typeof data === "object" && data !== null && "status" in data && typeof data.status === "string" && "jobId" in data && typeof data.jobId === "string";
1376
- }
1377
- function createJobsApi(fetcher) {
1378
- return {
1379
- async list(params, options) {
1380
- if (params) {
1381
- const result = request$5.query.safeParse(params);
1382
- if (!result.success) return validationErrorResult(result.error);
1383
- }
1384
- const queryString = buildQueryString(params);
1385
- return fetcher.get(`${BASE_PATH$6}${queryString}`, options);
1386
- },
1387
- async get(id, options) {
1388
- return fetcher.get(`${BASE_PATH$6}/${id}`, options);
1389
- },
1390
- async start(input, options) {
1391
- const result = request$6.body.safeParse(input);
1392
- if (!result.success) return validationErrorResult(result.error);
1393
- return fetcher.post(BASE_PATH$6, input, options);
1394
- },
1395
- async continue(id, input, options) {
1396
- const result = request$7.body.safeParse(input);
1397
- if (!result.success) return validationErrorResult(result.error);
1398
- return fetcher.post(`${BASE_PATH$6}/${id}/continue`, input, options);
1399
- },
1400
- async cancel(id, options) {
1401
- return fetcher.post(`${BASE_PATH$6}/${id}/cancel`, {}, options);
1402
- },
1403
- async stream(id, options) {
1404
- const result = await fetcher.getStream(`${BASE_PATH$6}/${id}/stream`, options);
1405
- if (!result.ok) return result;
1406
- async function* createEventGenerator(reader) {
1407
- try {
1408
- for await (const sseEvent of parseSSEEvents(reader)) if (sseEvent.event === "message") yield sseEvent.data;
1409
- else if (sseEvent.event === "error" && isErrorEventData(sseEvent.data)) throw new StreamError(sseEvent.data.type, sseEvent.data.jobId, sseEvent.data.message);
1410
- else if (sseEvent.event === "complete" && isCompleteEventData(sseEvent.data)) return;
1411
- } catch (error) {
1412
- if (error instanceof StreamError || error instanceof StreamConnectionError) throw error;
1413
- if (error instanceof DOMException && error.name === "AbortError") throw error;
1414
- throw new StreamConnectionError(error instanceof Error ? error.message : "Stream read error");
1415
- }
1416
- }
1417
- const reader = result.data.getReader();
1418
- return {
1419
- ok: true,
1420
- status: result.status,
1421
- headers: result.headers,
1422
- data: { events: createEventGenerator(reader) }
1423
- };
1424
- },
1425
- runs: createRunsApi(fetcher, BASE_PATH$6)
1426
- };
1427
- }
1428
- const BASE_PATH$5 = "/api/v1/applications";
1429
- function createApplicationsApi(fetcher) {
1430
- return {
1431
- async list(params, options) {
1432
- if (params) {
1433
- const result = request$20.query.safeParse(params);
1434
- if (!result.success) return validationErrorResult(result.error);
1435
- }
1436
- const queryString = buildQueryString(params);
1437
- return fetcher.get(`${BASE_PATH$5}${queryString}`, options);
1438
- },
1439
- async get(id, options) {
1440
- return fetcher.get(`${BASE_PATH$5}/${id}`, options);
1441
- },
1442
- async create(input, options) {
1443
- const result = request$21.body.safeParse(input);
1444
- if (!result.success) return validationErrorResult(result.error);
1445
- return fetcher.post(BASE_PATH$5, input, options);
1446
- },
1447
- async update(id, input, options) {
1448
- const result = request$19.body.safeParse(input);
1449
- if (!result.success) return validationErrorResult(result.error);
1450
- return fetcher.post(`${BASE_PATH$5}/${id}`, input, options);
1451
- },
1452
- async delete(id, options) {
1453
- return fetcher.delete(`${BASE_PATH$5}/${id}`, options);
1454
- }
1455
- };
1456
- }
1457
- const BASE_PATH$4 = "/api/v1/env/secrets";
1458
- function createSecretsApi(fetcher) {
1459
- return {
1460
- async list(params, options) {
1461
- if (params) {
1462
- const result = request$15.query.safeParse(params);
1463
- if (!result.success) return validationErrorResult(result.error);
1464
- }
1465
- const queryString = buildQueryString(params);
1466
- return fetcher.get(`${BASE_PATH$4}${queryString}`, options);
1467
- },
1468
- async get(name, params, options) {
1469
- const result = request$16.query.safeParse(params);
1470
- if (!result.success) return validationErrorResult(result.error);
1471
- const encodedName = encodeURIComponent(name);
1472
- const queryString = buildQueryString(params);
1473
- return fetcher.get(`${BASE_PATH$4}/${encodedName}${queryString}`, options);
1474
- },
1475
- async create(input, options) {
1476
- const result = request$18.body.safeParse(input);
1477
- if (!result.success) return validationErrorResult(result.error);
1478
- return fetcher.post(BASE_PATH$4, input, options);
1479
- },
1480
- async update(name, input, options) {
1481
- const result = request$14.body.safeParse(input);
1482
- if (!result.success) return validationErrorResult(result.error);
1483
- const encodedName = encodeURIComponent(name);
1484
- return fetcher.post(`${BASE_PATH$4}/${encodedName}`, input, options);
1485
- },
1486
- async delete(name, params, options) {
1487
- const result = request$17.query.safeParse(params);
1488
- if (!result.success) return validationErrorResult(result.error);
1489
- const encodedName = encodeURIComponent(name);
1490
- const queryString = buildQueryString(params);
1491
- return fetcher.deleteNoContent(`${BASE_PATH$4}/${encodedName}${queryString}`, options);
1492
- }
1493
- };
1494
- }
1495
- const BASE_PATH$3 = "/api/v1/env/variables";
1496
- function createVariablesApi(fetcher) {
1497
- return {
1498
- async list(params, options) {
1499
- const result = request$10.query.safeParse(params);
1500
- if (!result.success) return validationErrorResult(result.error);
1501
- const queryString = buildQueryString(params);
1502
- return fetcher.get(`${BASE_PATH$3}${queryString}`, options);
1503
- },
1504
- async get(name, params, options) {
1505
- const result = request$11.query.safeParse(params);
1506
- if (!result.success) return validationErrorResult(result.error);
1507
- const encodedName = encodeURIComponent(name);
1508
- const queryString = buildQueryString(params);
1509
- return fetcher.get(`${BASE_PATH$3}/${encodedName}${queryString}`, options);
1510
- },
1511
- async create(input, options) {
1512
- const result = request$13.body.safeParse(input);
1513
- if (!result.success) return validationErrorResult(result.error);
1514
- return fetcher.post(BASE_PATH$3, input, options);
1515
- },
1516
- async update(name, input, options) {
1517
- const result = request$9.body.safeParse(input);
1518
- if (!result.success) return validationErrorResult(result.error);
1519
- const encodedName = encodeURIComponent(name);
1520
- return fetcher.post(`${BASE_PATH$3}/${encodedName}`, input, options);
1521
- },
1522
- async delete(name, params, options) {
1523
- const result = request$12.query.safeParse(params);
1524
- if (!result.success) return validationErrorResult(result.error);
1525
- const encodedName = encodeURIComponent(name);
1526
- const queryString = buildQueryString(params);
1527
- return fetcher.deleteNoContent(`${BASE_PATH$3}/${encodedName}${queryString}`, options);
1528
- }
1529
- };
1530
- }
1531
- function createEnvApi(fetcher) {
1532
- return {
1533
- secrets: createSecretsApi(fetcher),
1534
- variables: createVariablesApi(fetcher)
1535
- };
1536
- }
1537
- function createVersionsApi(fetcher, basePath) {
1538
- return { async list(scopeName, options) {
1539
- const encodedScopeName = encodeURIComponent(scopeName);
1540
- return fetcher.get(`${basePath}/${encodedScopeName}/versions`, options);
1541
- } };
1542
- }
1543
- const BASE_PATH$2 = "/api/v1/experts";
1544
- function createExpertsApi(fetcher) {
1545
- return {
1546
- async list(params, options) {
1547
- if (params) {
1548
- const result = request$8.query.safeParse(params);
1549
- if (!result.success) return validationErrorResult(result.error);
1550
- }
1551
- const queryString = buildQueryString(params);
1552
- return fetcher.get(`${BASE_PATH$2}${queryString}`, options);
1553
- },
1554
- async get(key, options) {
1555
- const encodedKey = encodeURIComponent(key);
1556
- return fetcher.get(`${BASE_PATH$2}/${encodedKey}`, options);
1557
- },
1558
- async getFeatured(options) {
1559
- return fetcher.get(`${BASE_PATH$2}/featured`, options);
1560
- },
1561
- async getMeta(key, options) {
1562
- const encodedKey = encodeURIComponent(key);
1563
- return fetcher.get(`${BASE_PATH$2}/${encodedKey}/meta`, options);
1564
- },
1565
- async publish(scopeName, options) {
1566
- const encodedScopeName = encodeURIComponent(scopeName);
1567
- return fetcher.post(`${BASE_PATH$2}/${encodedScopeName}/publish`, {}, options);
1568
- },
1569
- async unpublish(scopeName, options) {
1570
- const encodedScopeName = encodeURIComponent(scopeName);
1571
- return fetcher.post(`${BASE_PATH$2}/${encodedScopeName}/unpublish`, {}, options);
1572
- },
1573
- async yank(key, options) {
1574
- const encodedKey = encodeURIComponent(key);
1575
- return fetcher.delete(`${BASE_PATH$2}/${encodedKey}`, options);
1576
- },
1577
- versions: createVersionsApi(fetcher, BASE_PATH$2)
1578
- };
1579
- }
1580
- const BASE_PATH$1 = "/api/v1/organizations";
1581
- function createOrganizationsApi(fetcher) {
1582
- return { async getCurrent(options) {
1583
- return fetcher.get(`${BASE_PATH$1}/current`, options);
1584
- } };
1585
- }
1586
- const BASE_PATH = "/api/v1/applications";
1587
- function createProviderSettingsApi(fetcher) {
1588
- return {
1589
- async list(applicationId, options) {
1590
- return fetcher.get(`${BASE_PATH}/${applicationId}/provider_settings`, options);
1591
- },
1592
- async get(applicationId, provider, options) {
1593
- const encodedProvider = encodeURIComponent(provider);
1594
- return fetcher.get(`${BASE_PATH}/${applicationId}/provider_settings/${encodedProvider}`, options);
1595
- },
1596
- async create(applicationId, input, options) {
1597
- const result = request$1.body.safeParse(input);
1598
- if (!result.success) return validationErrorResult(result.error);
1599
- return fetcher.post(`${BASE_PATH}/${applicationId}/provider_settings`, input, options);
1600
- },
1601
- async update(applicationId, provider, input, options) {
1602
- const result = request.body.safeParse(input);
1603
- if (!result.success) return validationErrorResult(result.error);
1604
- const encodedProvider = encodeURIComponent(provider);
1605
- return fetcher.post(`${BASE_PATH}/${applicationId}/provider_settings/${encodedProvider}`, input, options);
1606
- },
1607
- async delete(applicationId, provider, options) {
1608
- const encodedProvider = encodeURIComponent(provider);
1609
- return fetcher.deleteNoContent(`${BASE_PATH}/${applicationId}/provider_settings/${encodedProvider}`, options);
1610
- },
1611
- async listApiKeys(applicationId, provider, options) {
1612
- const encodedProvider = encodeURIComponent(provider);
1613
- return fetcher.get(`${BASE_PATH}/${applicationId}/provider_settings/${encodedProvider}/api_keys`, options);
1614
- },
1615
- async createApiKey(applicationId, provider, input, options) {
1616
- const result = request$2.body.safeParse(input);
1617
- if (!result.success) return validationErrorResult(result.error);
1618
- const encodedProvider = encodeURIComponent(provider);
1619
- return fetcher.post(`${BASE_PATH}/${applicationId}/provider_settings/${encodedProvider}/api_keys`, input, options);
1620
- },
1621
- async deleteApiKey(applicationId, provider, apiKeyId, options) {
1622
- const encodedProvider = encodeURIComponent(provider);
1623
- const encodedApiKeyId = encodeURIComponent(apiKeyId);
1624
- return fetcher.deleteNoContent(`${BASE_PATH}/${applicationId}/provider_settings/${encodedProvider}/api_keys/${encodedApiKeyId}`, options);
1625
- }
1626
- };
1627
- }
1628
- function createApiClient(config) {
1629
- const fetcher = createFetcher(config);
1630
- return {
1631
- applications: createApplicationsApi(fetcher),
1632
- env: createEnvApi(fetcher),
1633
- jobs: createJobsApi(fetcher),
1634
- experts: createExpertsApi(fetcher),
1635
- organizations: createOrganizationsApi(fetcher),
1636
- providerSettings: createProviderSettingsApi(fetcher)
1637
- };
1638
- }
1639
-
1640
- //#endregion
1641
- //#region ../../packages/runtime/src/helpers/resolve-expert.ts
1642
- async function resolveExpertToRun(expertKey, experts, clientOptions) {
1643
- if (experts[expertKey]) return experts[expertKey];
1644
- if (!clientOptions.perstackApiKey) throw new PerstackError(`PERSTACK_API_KEY is required to resolve published expert "${expertKey}"`);
1645
- const result = await createApiClient({
1646
- baseUrl: clientOptions.perstackApiBaseUrl,
1647
- apiKey: clientOptions.perstackApiKey
1648
- }).experts.get(expertKey);
1649
- if (!result.ok) throw new PerstackError(`Failed to resolve expert "${expertKey}": ${result.error.message}`);
1650
- const publishedExpert = result.data.data.definition.experts[expertKey];
1651
- if (!publishedExpert) throw new PerstackError(`Expert "${expertKey}" not found in API response`);
1652
- return toRuntimeExpert(expertKey, publishedExpert);
1653
- }
1654
- function toRuntimeExpert(key, expert) {
1655
- const skills = Object.fromEntries(Object.entries(expert.skills ?? {}).map(([name, skill]) => {
1656
- switch (skill.type) {
1657
- case "mcpStdioSkill": return [name, {
1658
- type: skill.type,
1659
- name,
1660
- description: skill.description,
1661
- rule: skill.rule,
1662
- pick: skill.pick ?? [],
1663
- omit: skill.omit ?? [],
1664
- command: skill.command,
1665
- packageName: skill.packageName,
1666
- requiredEnv: skill.requiredEnv ?? []
1667
- }];
1668
- case "mcpSseSkill": return [name, {
1669
- type: skill.type,
1670
- name,
1671
- description: skill.description,
1672
- rule: skill.rule,
1673
- pick: skill.pick ?? [],
1674
- omit: skill.omit ?? [],
1675
- endpoint: skill.endpoint
1676
- }];
1677
- case "interactiveSkill": return [name, {
1678
- type: skill.type,
1679
- name,
1680
- description: skill.description,
1681
- rule: skill.rule,
1682
- tools: Object.fromEntries(Object.entries(skill.tools).map(([toolName, tool]) => [toolName, {
1683
- name: toolName,
1684
- description: tool.description,
1685
- inputSchema: JSON.parse(tool.inputJsonSchema)
1686
- }]))
1687
- }];
1688
- default: throw new PerstackError(`Unknown skill type: ${skill.type}`);
1689
- }
1690
- }));
1691
- return {
1692
- key,
1693
- name: expert.name,
1694
- version: expert.version,
1695
- minRuntimeVersion: expert.minRuntimeVersion ?? "v1.0",
1696
- description: expert.description ?? "",
1697
- instruction: expert.instruction,
1698
- skills,
1699
- delegates: expert.delegates ?? [],
1700
- tags: expert.tags ?? []
1701
- };
1702
- }
1703
-
1704
- //#endregion
1705
- export { resolveExpertToRun };
1706
- //# sourceMappingURL=resolve-expert-Circ5eKU.js.map