@perstack/api-client 0.0.45 → 0.0.47

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/dist/index.mjs ADDED
@@ -0,0 +1,2011 @@
1
+ import { r as __toESM, t as __commonJSMin } from "./chunk-Bdv87wj9.mjs";
2
+ import { z } from "zod";
3
+ import { activityOrGroupSchema, checkpointSchema as perstackCheckpointSchema, instructionMessageSchema, messageSchema, stepSchema, toolCallSchema, toolMessageSchema, toolResultSchema, usageSchema, userMessageSchema } from "@perstack/core";
4
+
5
+ //#region ../constants/index.ts
6
+ const organizationNameRegex = /^[a-z0-9][a-z0-9_.-]*$/;
7
+ const maxOrganizationNameLength = 128;
8
+ const maxApplicationNameLength = 255;
9
+ 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_.-]*))?$/;
10
+ const expertNameRegex = /^(@[a-z0-9][a-z0-9_-]*\/)?[a-z0-9][a-z0-9_-]*$/;
11
+ const scopeNameRegex = /^[a-z0-9][a-z0-9_-]*$/;
12
+ 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_-]*))?$/;
13
+ const expertVersionRegex = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/;
14
+ const tagNameRegex = /^[a-z0-9][a-z0-9_-]*$/;
15
+ const maxExpertNameLength = 255;
16
+ const maxExpertVersionTagLength = 255;
17
+ const maxExpertKeyLength = 511;
18
+ const maxExpertDescriptionLength = 1024 * 2;
19
+ const maxExpertInstructionLength = 1024 * 20;
20
+ const maxExpertDelegateItems = 255;
21
+ const maxExpertTagItems = 8;
22
+ const maxExpertJobQueryLength = 1024 * 20;
23
+ const maxExpertJobFileNameLength = 1024 * 10;
24
+ 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_.-]*)?$/;
25
+ const urlSafeRegex = /^[a-z0-9][a-z0-9_-]*$/;
26
+ const maxSkillNameLength = 255;
27
+ const maxSkillDescriptionLength = 1024 * 2;
28
+ const maxSkillRuleLength = 1024 * 2;
29
+ const maxSkillPickOmitItems = 255;
30
+ const maxSkillRequiredEnvItems = 255;
31
+ const maxSkillToolNameLength = 255;
32
+ const maxSkillEndpointLength = 1024 * 2;
33
+ const maxSkillInputJsonSchemaLength = 1024 * 20;
34
+ const maxCheckpointToolCallIdLength = 255;
35
+ const envNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
36
+ const maxEnvNameLength = 255;
37
+ const maxProviderBaseUrlLength = 2048;
38
+ const maxProviderHeaderKeyLength = 255;
39
+ const maxProviderHeaderValueLength = 2048;
40
+ const maxProviderHeadersCount = 50;
41
+
42
+ //#endregion
43
+ //#region ../models/src/domain/common.ts
44
+ const cuidSchema = z.cuid2();
45
+ const runtimeVersionSchema = z.enum(["v1.0"]);
46
+ const providerSchema = z.enum([
47
+ "anthropic",
48
+ "google",
49
+ "openai",
50
+ "ollama",
51
+ "deepseek",
52
+ "azure-openai",
53
+ "amazon-bedrock",
54
+ "google-vertex"
55
+ ]);
56
+ const datetimeSchema = z.string().datetime();
57
+ const expertKeyFieldSchema = z.string().min(1).max(maxExpertKeyLength).regex(expertKeyRegex);
58
+ const expertNameFieldSchema = z.string().min(1).max(maxExpertNameLength).regex(expertNameRegex);
59
+ const expertVersionFieldSchema = z.string().min(1).max(maxExpertVersionTagLength).regex(expertVersionRegex);
60
+ const expertTagFieldSchema = z.string().min(1).max(maxExpertVersionTagLength).regex(tagNameRegex);
61
+ const expertCategoryFieldSchema = z.enum([
62
+ "general",
63
+ "coding",
64
+ "research",
65
+ "writing",
66
+ "data",
67
+ "automation"
68
+ ]);
69
+ const scopeNameSchema = z.string().min(1).max(maxExpertNameLength).regex(scopeNameRegex);
70
+ const scopeNameRefSchema = z.string().min(1).max(maxExpertNameLength + maxExpertVersionTagLength + 1).regex(scopeNameRefRegex);
71
+ const draftRefFieldSchema = z.string().min(1).max(30);
72
+
73
+ //#endregion
74
+ //#region ../models/src/domain/organization.ts
75
+ const organizationStatusSchema = z.enum([
76
+ "active",
77
+ "inactive",
78
+ "deleted"
79
+ ]);
80
+ const organizationTypeSchema = z.enum([
81
+ "personal",
82
+ "personalPlus",
83
+ "team",
84
+ "serviceAdmin"
85
+ ]);
86
+ const organizationSchema = z.object({
87
+ type: z.literal("organization"),
88
+ id: cuidSchema,
89
+ createdAt: datetimeSchema,
90
+ updatedAt: datetimeSchema,
91
+ name: z.string().min(1).max(maxOrganizationNameLength).regex(organizationNameRegex).optional(),
92
+ nameChangedAt: datetimeSchema.optional(),
93
+ status: organizationStatusSchema,
94
+ organizationType: organizationTypeSchema,
95
+ maxApplications: z.number().int().min(0),
96
+ maxApiKeys: z.number().int().min(0),
97
+ maxExperts: z.number().int().min(0)
98
+ });
99
+
100
+ //#endregion
101
+ //#region ../models/src/domain/application.ts
102
+ const applicationNameSchema = z.string().min(1).max(maxApplicationNameLength);
103
+ const applicationStatusSchema = z.enum([
104
+ "active",
105
+ "inactive",
106
+ "deleted"
107
+ ]);
108
+ const applicationSchema = z.object({
109
+ type: z.literal("application"),
110
+ id: cuidSchema,
111
+ organizationId: cuidSchema,
112
+ organization: organizationSchema,
113
+ createdAt: datetimeSchema,
114
+ updatedAt: datetimeSchema,
115
+ name: applicationNameSchema,
116
+ status: applicationStatusSchema
117
+ });
118
+
119
+ //#endregion
120
+ //#region ../models/src/api/applications/create.ts
121
+ const request$38 = { body: z.object({
122
+ name: applicationNameSchema,
123
+ applicationGroupId: cuidSchema.optional()
124
+ }) };
125
+ const response$40 = z.object({ data: z.object({ application: applicationSchema }) });
126
+
127
+ //#endregion
128
+ //#region ../models/src/api/applications/delete.ts
129
+ const request$37 = { params: z.object({ applicationId: cuidSchema }) };
130
+ const response$39 = z.object({ data: z.object({ application: applicationSchema }) });
131
+
132
+ //#endregion
133
+ //#region ../models/src/api/applications/get.ts
134
+ const request$36 = { params: z.object({ applicationId: cuidSchema }) };
135
+ const response$38 = z.object({ data: z.object({ application: applicationSchema }) });
136
+
137
+ //#endregion
138
+ //#region ../../node_modules/ts-dedent/dist/index.js
139
+ var require_dist = /* @__PURE__ */ __commonJSMin(((exports) => {
140
+ Object.defineProperty(exports, "__esModule", { value: true });
141
+ exports.dedent = void 0;
142
+ function dedent(templ) {
143
+ var values = [];
144
+ for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
145
+ var strings = Array.from(typeof templ === "string" ? [templ] : templ);
146
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
147
+ var indentLengths = strings.reduce(function(arr, str) {
148
+ var matches = str.match(/\n([\t ]+|(?!\s).)/g);
149
+ if (matches) return arr.concat(matches.map(function(match) {
150
+ var _a, _b;
151
+ return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
152
+ }));
153
+ return arr;
154
+ }, []);
155
+ if (indentLengths.length) {
156
+ var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
157
+ strings = strings.map(function(str) {
158
+ return str.replace(pattern_1, "\n");
159
+ });
160
+ }
161
+ strings[0] = strings[0].replace(/^\r?\n/, "");
162
+ var string = strings[0];
163
+ values.forEach(function(value, i) {
164
+ var endentations = string.match(/(?:^|\n)( *)$/);
165
+ var endentation = endentations ? endentations[1] : "";
166
+ var indentedValue = value;
167
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i$1) {
168
+ return i$1 === 0 ? str : "" + endentation + str;
169
+ }).join("\n");
170
+ string += indentedValue + strings[i + 1];
171
+ });
172
+ return string;
173
+ }
174
+ exports.dedent = dedent;
175
+ exports.default = dedent;
176
+ }));
177
+
178
+ //#endregion
179
+ //#region ../models/src/api/common.ts
180
+ var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1);
181
+ const errorBadRequest = z.object({
182
+ code: z.literal(400),
183
+ error: z.literal("Bad Request"),
184
+ reason: z.string()
185
+ }).describe("Bad Request");
186
+ const errorUnauthorized = z.object({
187
+ code: z.literal(401),
188
+ error: z.literal("Unauthorized"),
189
+ reason: z.literal("Failed to authenticate")
190
+ }).describe(import_dist.default`
191
+ Authentication failed. Possible reasons:
192
+ - Authorization header is not provided
193
+ - Invalid API key
194
+ - Session expired
195
+ `);
196
+ const errorForbidden = z.object({
197
+ code: z.literal(403),
198
+ error: z.literal("Forbidden"),
199
+ reason: z.string()
200
+ }).describe("Access denied. The authenticated user does not have permission to perform this action.");
201
+ const errorNotFound = z.object({
202
+ code: z.literal(404),
203
+ error: z.literal("Not Found"),
204
+ reason: z.string()
205
+ }).describe("Resource not found.");
206
+ const errorValidationFailed = z.object({
207
+ code: z.literal(422),
208
+ error: z.literal("Validation Failed"),
209
+ reason: z.unknown()
210
+ }).describe("Request validation failed. Check the request body, query parameters, or path parameters.");
211
+ const paginationMeta = z.object({
212
+ total: z.number().int().min(0),
213
+ take: z.number().int().min(1),
214
+ skip: z.number().int().min(0)
215
+ });
216
+ const errorUnauthorizedFlexible = z.object({
217
+ code: z.literal(401),
218
+ error: z.literal("Unauthorized"),
219
+ reason: z.string()
220
+ }).describe("Unauthorized");
221
+
222
+ //#endregion
223
+ //#region ../models/src/api/applications/getAll.ts
224
+ const request$35 = { query: z.object({
225
+ name: z.union([z.string(), z.array(z.string())]).optional().transform((v) => Array.isArray(v) ? v.join(",") : v),
226
+ sort: z.enum([
227
+ "name",
228
+ "createdAt",
229
+ "updatedAt"
230
+ ]).optional(),
231
+ order: z.enum(["asc", "desc"]).optional(),
232
+ take: z.coerce.number().min(1).max(100).default(100),
233
+ skip: z.coerce.number().min(0).default(0)
234
+ }) };
235
+ const response$37 = z.object({
236
+ data: z.object({ applications: z.array(applicationSchema) }),
237
+ meta: paginationMeta
238
+ });
239
+
240
+ //#endregion
241
+ //#region ../models/src/api/applications/update.ts
242
+ const request$34 = {
243
+ params: z.object({ applicationId: cuidSchema }),
244
+ body: z.object({
245
+ name: applicationNameSchema.optional(),
246
+ status: applicationStatusSchema.exclude(["deleted"]).optional()
247
+ }).refine((data) => data.name !== void 0 || data.status !== void 0, { message: "At least one field must be provided" })
248
+ };
249
+ const response$36 = z.object({ data: z.object({ application: applicationSchema }) });
250
+
251
+ //#endregion
252
+ //#region ../models/src/domain/secret.ts
253
+ const secretNameSchema = z.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");
254
+ const secretValueSchema = z.string().min(1, "Secret value is required");
255
+ const secretMetadataSchema = z.object({
256
+ name: z.string(),
257
+ createdAt: datetimeSchema,
258
+ updatedAt: datetimeSchema
259
+ });
260
+ const secretSchema = z.object({
261
+ type: z.literal("secret"),
262
+ id: cuidSchema,
263
+ name: secretNameSchema,
264
+ applicationId: cuidSchema,
265
+ createdAt: datetimeSchema,
266
+ updatedAt: datetimeSchema
267
+ });
268
+
269
+ //#endregion
270
+ //#region ../models/src/api/env/secrets/create.ts
271
+ const request$33 = { body: z.object({
272
+ applicationId: cuidSchema,
273
+ name: secretNameSchema,
274
+ value: secretValueSchema
275
+ }) };
276
+ const response$35 = z.object({ data: z.object({ secret: secretMetadataSchema }) });
277
+
278
+ //#endregion
279
+ //#region ../models/src/api/env/secrets/delete.ts
280
+ const request$32 = {
281
+ params: z.object({ name: z.string().min(1) }),
282
+ query: z.object({ applicationId: cuidSchema })
283
+ };
284
+ const response$34 = z.null();
285
+
286
+ //#endregion
287
+ //#region ../models/src/api/env/secrets/get.ts
288
+ const request$31 = {
289
+ params: z.object({ name: z.string().min(1) }),
290
+ query: z.object({ applicationId: cuidSchema })
291
+ };
292
+ const response$33 = z.object({ data: z.object({ secret: secretMetadataSchema }) });
293
+
294
+ //#endregion
295
+ //#region ../models/src/api/env/secrets/getAll.ts
296
+ const request$30 = { query: z.object({ applicationId: cuidSchema.optional() }) };
297
+ const response$32 = z.object({ data: z.object({ secrets: z.array(secretMetadataSchema) }) });
298
+
299
+ //#endregion
300
+ //#region ../models/src/api/env/secrets/update.ts
301
+ const request$29 = {
302
+ params: z.object({ name: z.string().min(1) }),
303
+ body: z.object({
304
+ applicationId: cuidSchema,
305
+ value: secretValueSchema
306
+ })
307
+ };
308
+ const response$31 = z.object({ data: z.object({ secret: secretMetadataSchema }) });
309
+
310
+ //#endregion
311
+ //#region ../models/src/domain/variable.ts
312
+ const variableNameSchema = z.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/, "Variable name must start with uppercase letter or underscore, and contain only uppercase letters, digits, and underscores");
313
+ const variableValueSchema = z.string();
314
+ const variableSchema = z.object({
315
+ type: z.literal("variable"),
316
+ id: cuidSchema,
317
+ applicationId: cuidSchema,
318
+ createdAt: datetimeSchema,
319
+ updatedAt: datetimeSchema,
320
+ name: variableNameSchema,
321
+ value: variableValueSchema
322
+ });
323
+ const variableResponseSchema = z.object({
324
+ name: variableNameSchema,
325
+ value: variableValueSchema,
326
+ createdAt: datetimeSchema,
327
+ updatedAt: datetimeSchema
328
+ });
329
+
330
+ //#endregion
331
+ //#region ../models/src/api/env/variables/create.ts
332
+ const request$28 = { body: z.object({
333
+ applicationId: cuidSchema,
334
+ name: variableNameSchema,
335
+ value: variableValueSchema
336
+ }) };
337
+ const response$30 = z.object({ data: z.object({ variable: variableResponseSchema }) });
338
+
339
+ //#endregion
340
+ //#region ../models/src/api/env/variables/delete.ts
341
+ const request$27 = {
342
+ params: z.object({ name: z.string().min(1) }),
343
+ query: z.object({ applicationId: cuidSchema })
344
+ };
345
+ const response$29 = z.null();
346
+
347
+ //#endregion
348
+ //#region ../models/src/api/env/variables/get.ts
349
+ const request$26 = {
350
+ params: z.object({ name: z.string().min(1) }),
351
+ query: z.object({ applicationId: cuidSchema })
352
+ };
353
+ const response$28 = z.object({ data: z.object({ variable: variableResponseSchema }) });
354
+
355
+ //#endregion
356
+ //#region ../models/src/api/env/variables/getAll.ts
357
+ const request$25 = { query: z.object({ applicationId: cuidSchema }) };
358
+ const response$27 = z.object({ data: z.object({ variables: z.array(variableResponseSchema) }) });
359
+
360
+ //#endregion
361
+ //#region ../models/src/api/env/variables/update.ts
362
+ const request$24 = {
363
+ params: z.object({ name: z.string().min(1) }),
364
+ body: z.object({
365
+ applicationId: cuidSchema,
366
+ value: variableValueSchema
367
+ })
368
+ };
369
+ const response$26 = z.object({ data: z.object({ variable: variableResponseSchema }) });
370
+
371
+ //#endregion
372
+ //#region ../models/src/domain/expertScope.ts
373
+ const expertScopeSchema = z.object({
374
+ id: cuidSchema,
375
+ name: scopeNameSchema,
376
+ organizationId: cuidSchema,
377
+ published: z.boolean(),
378
+ publishedAt: datetimeSchema.optional(),
379
+ category: expertCategoryFieldSchema,
380
+ totalRuns: z.number().int().min(0),
381
+ totalJobs: z.number().int().min(0),
382
+ totalStars: z.number().int().min(0),
383
+ createdAt: datetimeSchema,
384
+ updatedAt: datetimeSchema,
385
+ createdBy: cuidSchema,
386
+ updatedBy: cuidSchema
387
+ });
388
+ const expertVersionSchema = z.object({
389
+ id: cuidSchema,
390
+ expertScopeId: cuidSchema,
391
+ version: expertVersionFieldSchema,
392
+ public: z.boolean(),
393
+ yanked: z.boolean(),
394
+ totalRuns: z.number().int().min(0),
395
+ totalJobs: z.number().int().min(0),
396
+ createdAt: datetimeSchema,
397
+ updatedAt: datetimeSchema,
398
+ createdBy: cuidSchema,
399
+ updatedBy: cuidSchema,
400
+ tags: z.array(expertTagFieldSchema)
401
+ });
402
+ const expertScopeWithVersionsSchema = expertScopeSchema.extend({ versions: z.array(expertVersionSchema) });
403
+
404
+ //#endregion
405
+ //#region ../models/src/domain/skill.ts
406
+ function isPrivateOrLocalIP(hostname) {
407
+ if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "0.0.0.0") return true;
408
+ const ipv4Match = hostname.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
409
+ if (ipv4Match) {
410
+ const a = Number(ipv4Match[1]);
411
+ const b = Number(ipv4Match[2]);
412
+ if (a === 10) return true;
413
+ if (a === 172 && b >= 16 && b <= 31) return true;
414
+ if (a === 192 && b === 168) return true;
415
+ if (a === 169 && b === 254) return true;
416
+ if (a === 127) return true;
417
+ }
418
+ if (hostname.includes(":")) {
419
+ if (hostname.startsWith("fe80:") || hostname.startsWith("fc") || hostname.startsWith("fd")) return true;
420
+ }
421
+ if (hostname.startsWith("::ffff:")) {
422
+ if (isPrivateOrLocalIP(hostname.slice(7))) return true;
423
+ }
424
+ return false;
425
+ }
426
+ const sseEndpointSchema = z.string().max(maxSkillEndpointLength).url().refine((url) => {
427
+ try {
428
+ const parsed = new URL(url);
429
+ if (parsed.protocol !== "https:") return false;
430
+ if (isPrivateOrLocalIP(parsed.hostname)) return false;
431
+ return true;
432
+ } catch {
433
+ return false;
434
+ }
435
+ }, { message: "Endpoint must be a public HTTPS URL" });
436
+ const skillNameSchema = z.string().min(1).max(maxSkillNameLength).regex(packageWithVersionRegex);
437
+ const mcpStdioSkillCommandSchema = z.enum(["npx", "uvx"]);
438
+ const mcpStdioSkillSchema = z.object({
439
+ type: z.literal("mcpStdioSkill"),
440
+ name: z.string(),
441
+ description: z.string().min(1).max(maxSkillDescriptionLength),
442
+ rule: z.string().min(1).max(maxSkillRuleLength).optional(),
443
+ pick: z.array(z.string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
444
+ omit: z.array(z.string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
445
+ command: mcpStdioSkillCommandSchema,
446
+ packageName: z.string().min(1).max(maxSkillNameLength).regex(packageWithVersionRegex),
447
+ requiredEnv: z.array(z.string().min(1).max(maxEnvNameLength).regex(envNameRegex)).min(0).max(maxSkillRequiredEnvItems).optional()
448
+ });
449
+ const mcpSseSkillSchema = z.object({
450
+ type: z.literal("mcpSseSkill"),
451
+ name: z.string(),
452
+ description: z.string().min(1).max(maxSkillDescriptionLength),
453
+ rule: z.string().min(1).max(maxSkillRuleLength).optional(),
454
+ pick: z.array(z.string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
455
+ omit: z.array(z.string().min(1).max(maxSkillToolNameLength)).max(maxSkillPickOmitItems).optional().default([]),
456
+ endpoint: sseEndpointSchema
457
+ });
458
+ const interactiveSkillSchema = z.object({
459
+ type: z.literal("interactiveSkill"),
460
+ name: z.string(),
461
+ description: z.string().min(1).max(maxSkillDescriptionLength),
462
+ rule: z.string().min(1).max(maxSkillRuleLength).optional(),
463
+ tools: z.record(z.string().min(1).max(maxSkillToolNameLength).regex(urlSafeRegex), z.object({
464
+ description: z.string().min(1).max(maxSkillDescriptionLength),
465
+ inputJsonSchema: z.string().min(1).max(maxSkillInputJsonSchemaLength)
466
+ }))
467
+ });
468
+ const skillSchema = z.discriminatedUnion("type", [
469
+ mcpStdioSkillSchema,
470
+ mcpSseSkillSchema,
471
+ interactiveSkillSchema
472
+ ]);
473
+
474
+ //#endregion
475
+ //#region ../models/src/domain/expert.ts
476
+ const expertSchema = z.object({
477
+ key: expertKeyFieldSchema,
478
+ name: expertNameFieldSchema,
479
+ version: expertVersionFieldSchema,
480
+ description: z.string().min(1).max(maxExpertDescriptionLength).optional(),
481
+ instruction: z.string().min(1).max(maxExpertInstructionLength),
482
+ skills: z.record(skillNameSchema, skillSchema).optional().default({}),
483
+ delegates: z.array(expertKeyFieldSchema).min(0).max(maxExpertDelegateItems).optional().default([]),
484
+ tags: z.array(expertTagFieldSchema).min(0).max(maxExpertTagItems).optional().default([])
485
+ });
486
+ const expertMetadataSchema = z.object({
487
+ scope: expertScopeSchema,
488
+ version: expertVersionSchema
489
+ });
490
+ const expertWithMetadataSchema = expertSchema.extend({
491
+ scope: expertScopeSchema,
492
+ version: expertVersionSchema
493
+ });
494
+
495
+ //#endregion
496
+ //#region ../models/src/api/experts/definition.ts
497
+ const expertDefinitionSchema = z.object({
498
+ name: expertNameFieldSchema,
499
+ version: expertVersionFieldSchema,
500
+ organizationId: cuidSchema,
501
+ createdAt: datetimeSchema,
502
+ updatedAt: datetimeSchema,
503
+ createdBy: cuidSchema,
504
+ updatedBy: cuidSchema,
505
+ experts: z.record(expertKeyFieldSchema, expertSchema.omit({ key: true }))
506
+ });
507
+
508
+ //#endregion
509
+ //#region ../models/src/api/experts/delete.ts
510
+ const request$23 = { params: z.object({ scopeName: scopeNameRefSchema }) };
511
+ const response$25 = z.object({ data: expertMetadataSchema.extend({
512
+ yanked: z.literal(true),
513
+ latestTagUpdated: z.boolean()
514
+ }) });
515
+
516
+ //#endregion
517
+ //#region ../models/src/domain/expertDraftScope.ts
518
+ const expertDraftScopeSchema = z.object({
519
+ id: cuidSchema,
520
+ name: scopeNameSchema,
521
+ organizationId: cuidSchema,
522
+ applicationId: cuidSchema,
523
+ totalRuns: z.number().int().min(0),
524
+ totalJobs: z.number().int().min(0),
525
+ createdAt: datetimeSchema,
526
+ updatedAt: datetimeSchema,
527
+ createdBy: cuidSchema,
528
+ updatedBy: cuidSchema
529
+ });
530
+ const expertDraftRefSchema = z.object({
531
+ id: cuidSchema,
532
+ expertDraftScopeId: cuidSchema,
533
+ totalRuns: z.number().int().min(0),
534
+ totalJobs: z.number().int().min(0),
535
+ createdAt: datetimeSchema,
536
+ updatedAt: datetimeSchema,
537
+ createdBy: cuidSchema,
538
+ updatedBy: cuidSchema
539
+ });
540
+ const expertDraftScopeWithRefsSchema = expertDraftScopeSchema.extend({ draftRefs: z.array(expertDraftRefSchema) });
541
+
542
+ //#endregion
543
+ //#region ../models/src/api/experts/drafts/definition.ts
544
+ const expertDefinitionContentSchema = z.object({
545
+ name: expertNameFieldSchema,
546
+ version: z.literal("0.0.0-draft"),
547
+ applicationId: cuidSchema,
548
+ createdAt: datetimeSchema,
549
+ updatedAt: datetimeSchema,
550
+ createdBy: cuidSchema,
551
+ updatedBy: cuidSchema,
552
+ experts: z.record(expertKeyFieldSchema, expertSchema.omit({ key: true }))
553
+ });
554
+
555
+ //#endregion
556
+ //#region ../models/src/api/experts/drafts/create.ts
557
+ const request$22 = {
558
+ params: z.object({ scopeName: scopeNameSchema }),
559
+ body: z.object({
560
+ applicationId: cuidSchema,
561
+ experts: z.array(expertSchema)
562
+ })
563
+ };
564
+ const response$24 = z.object({ data: z.object({
565
+ scope: expertDraftScopeSchema,
566
+ draftRef: expertDraftRefSchema,
567
+ definition: expertDefinitionContentSchema
568
+ }) });
569
+
570
+ //#endregion
571
+ //#region ../models/src/api/experts/drafts/delete.ts
572
+ const request$21 = { params: z.object({
573
+ scopeName: scopeNameSchema,
574
+ draftRef: expertDraftRefSchema.shape.id
575
+ }) };
576
+ const response$23 = z.object({ data: z.object({
577
+ deleted: z.boolean(),
578
+ draftRef: z.string()
579
+ }) });
580
+
581
+ //#endregion
582
+ //#region ../models/src/api/experts/drafts/get.ts
583
+ const request$20 = { params: z.object({
584
+ scopeName: scopeNameSchema,
585
+ draftRef: expertDraftRefSchema.shape.id
586
+ }) };
587
+ const response$22 = z.object({ data: z.object({
588
+ scope: expertDraftScopeSchema,
589
+ draftRef: expertDraftRefSchema,
590
+ definition: expertDefinitionContentSchema
591
+ }) });
592
+
593
+ //#endregion
594
+ //#region ../models/src/api/experts/drafts/getAll.ts
595
+ const request$19 = {
596
+ params: z.object({ scopeName: expertDraftScopeSchema.shape.name }),
597
+ query: z.object({
598
+ limit: z.coerce.number().int().min(1).max(100).optional().default(20),
599
+ offset: z.coerce.number().int().min(0).optional().default(0)
600
+ })
601
+ };
602
+ const response$21 = z.object({ data: z.object({
603
+ draftRefs: z.array(expertDraftRefSchema),
604
+ total: z.number().int().min(0)
605
+ }) });
606
+
607
+ //#endregion
608
+ //#region ../models/src/api/experts/drafts/update.ts
609
+ const request$18 = {
610
+ params: z.object({
611
+ scopeName: scopeNameSchema,
612
+ draftRef: expertDraftRefSchema.shape.id
613
+ }),
614
+ body: z.object({ experts: z.array(expertSchema) })
615
+ };
616
+ const response$20 = z.object({ data: z.object({
617
+ scope: expertDraftScopeSchema,
618
+ draftRef: expertDraftRefSchema,
619
+ definition: expertDefinitionContentSchema
620
+ }) });
621
+
622
+ //#endregion
623
+ //#region ../models/src/api/experts/drafts/version.ts
624
+ const request$17 = {
625
+ params: z.object({
626
+ scopeName: scopeNameSchema,
627
+ draftRef: z.string().min(1)
628
+ }),
629
+ body: z.object({
630
+ version: z.string().min(1, "Version is required.").max(maxExpertVersionTagLength, "Version is too long.").regex(expertVersionRegex, "Invalid version format. (e.g. 1.0.0)"),
631
+ tag: z.string().max(maxExpertVersionTagLength, "Tag is too long.").regex(tagNameRegex, "Invalid tag format. (e.g. latest)").optional()
632
+ })
633
+ };
634
+ const response$19 = z.object({ data: z.object({
635
+ scope: expertScopeSchema,
636
+ version: expertVersionSchema,
637
+ definitionUrl: z.string()
638
+ }) });
639
+
640
+ //#endregion
641
+ //#region ../models/src/api/experts/featured.ts
642
+ const response$18 = z.object({ data: z.object({ featuredExperts: z.array(z.object({
643
+ scope: expertScopeSchema,
644
+ currentVersion: expertVersionSchema,
645
+ displayOrder: z.number().int().min(0).max(2),
646
+ featuredAt: z.string().datetime()
647
+ })) }) });
648
+
649
+ //#endregion
650
+ //#region ../models/src/api/experts/get.ts
651
+ const request$16 = { params: z.object({ scopeName: scopeNameRefSchema }) };
652
+ const response$17 = z.object({ data: z.object({
653
+ definition: expertDefinitionSchema,
654
+ yanked: z.boolean().optional()
655
+ }) });
656
+
657
+ //#endregion
658
+ //#region ../models/src/api/experts/getAll.ts
659
+ const request$15 = { query: z.object({
660
+ filter: z.string().describe("Filter by scope name (partial match)").optional(),
661
+ category: z.enum([
662
+ "general",
663
+ "coding",
664
+ "research",
665
+ "writing",
666
+ "data",
667
+ "automation"
668
+ ]).describe("Filter by category").optional(),
669
+ includeDrafts: z.coerce.boolean().default(false).describe("Include unpublished scopes (owner only)").optional(),
670
+ limit: z.coerce.number().min(1).max(100).default(20).describe("Maximum results").optional(),
671
+ offset: z.coerce.number().min(0).default(0).describe("Pagination offset").optional()
672
+ }) };
673
+ const response$16 = z.object({ data: z.object({
674
+ experts: z.array(expertScopeSchema.extend({ currentVersion: expertVersionSchema })),
675
+ total: z.number()
676
+ }) });
677
+
678
+ //#endregion
679
+ //#region ../models/src/api/experts/meta.ts
680
+ const request$14 = {
681
+ params: z.object({ scopeName: scopeNameRefSchema }),
682
+ query: z.object({ public: z.enum(["true", "false"]).transform((val) => val === "true").optional().default(false).describe("Public access check (no auth)") })
683
+ };
684
+ const response$15 = z.object({ data: expertMetadataSchema.extend({ definitionUrl: z.string() }) });
685
+
686
+ //#endregion
687
+ //#region ../models/src/api/experts/publish.ts
688
+ const request$13 = { params: z.object({ scopeName: scopeNameSchema }) };
689
+ const response$14 = z.object({ data: z.object({ scope: expertScopeSchema }) });
690
+
691
+ //#endregion
692
+ //#region ../models/src/api/experts/unpublish.ts
693
+ const request$12 = { params: z.object({ scopeName: scopeNameSchema }) };
694
+ const response$13 = z.object({ data: z.object({ scope: expertScopeSchema }) });
695
+
696
+ //#endregion
697
+ //#region ../models/src/api/experts/versions.ts
698
+ const request$11 = { params: z.object({ scopeName: scopeNameSchema }) };
699
+ const response$12 = z.object({ data: z.object({ versions: z.array(expertVersionSchema) }) });
700
+
701
+ //#endregion
702
+ //#region ../models/src/domain/checkpoint.ts
703
+ const delegationTargetSchema = z.object({
704
+ expert: expertSchema,
705
+ toolCallId: z.string().min(1).max(maxCheckpointToolCallIdLength),
706
+ toolName: z.string().min(1).max(maxSkillToolNameLength),
707
+ query: z.string()
708
+ });
709
+ /**
710
+ * API Checkpoint schema - extended checkpoint format for API responses.
711
+ * Includes additional fields computed from runtime checkpoint and step data:
712
+ * - activities: computed via getActivities() from @perstack/core
713
+ * - inputMessages, newMessages, toolCalls, toolResults: step-related data
714
+ * - expert: full Expert type (with instruction, skills, etc.)
715
+ * - startedAt/finishedAt: ISO string format (runtime uses Unix timestamps)
716
+ */
717
+ const apiCheckpointSchema = z.object({
718
+ type: z.literal("checkpoint"),
719
+ id: cuidSchema,
720
+ jobId: cuidSchema,
721
+ runId: cuidSchema,
722
+ activities: z.array(activityOrGroupSchema),
723
+ stepNumber: z.number().int().min(1),
724
+ status: z.enum([
725
+ "init",
726
+ "proceeding",
727
+ "completed",
728
+ "stoppedByInteractiveTool",
729
+ "stoppedByDelegate",
730
+ "stoppedByExceededMaxSteps",
731
+ "stoppedByError"
732
+ ]),
733
+ expert: expertSchema,
734
+ delegateTo: z.array(delegationTargetSchema).optional(),
735
+ delegatedBy: z.object({
736
+ expert: expertSchema,
737
+ toolCallId: z.string().min(1).max(maxCheckpointToolCallIdLength),
738
+ toolName: z.string().min(1).max(maxSkillToolNameLength),
739
+ checkpointId: cuidSchema,
740
+ runId: cuidSchema
741
+ }).optional(),
742
+ inputMessages: z.array(z.union([
743
+ instructionMessageSchema,
744
+ userMessageSchema,
745
+ toolMessageSchema
746
+ ])).optional(),
747
+ messages: z.array(messageSchema),
748
+ newMessages: z.array(messageSchema),
749
+ toolCalls: z.array(toolCallSchema).optional(),
750
+ toolResults: z.array(toolResultSchema).optional(),
751
+ pendingToolCalls: z.array(toolCallSchema).optional(),
752
+ partialToolResults: z.array(toolResultSchema).optional(),
753
+ usage: usageSchema,
754
+ contextWindow: z.number().int().min(0).optional(),
755
+ contextWindowUsage: z.number().int().min(0).optional(),
756
+ error: z.object({
757
+ name: z.string(),
758
+ message: z.string(),
759
+ statusCode: z.number().optional(),
760
+ isRetryable: z.boolean()
761
+ }).optional(),
762
+ retryCount: z.number().optional(),
763
+ startedAt: datetimeSchema,
764
+ finishedAt: datetimeSchema.optional()
765
+ });
766
+
767
+ //#endregion
768
+ //#region ../models/src/api/jobs/checkpoints/create.ts
769
+ /**
770
+ * Request checkpoint schema - `id` and `runId` are omitted because:
771
+ * - `id` is server-generated (CUID)
772
+ * - `runId` is optional in request, server will use job's run ID
773
+ */
774
+ const requestCheckpointSchema = perstackCheckpointSchema.omit({
775
+ id: true,
776
+ runId: true
777
+ }).extend({ runId: z.string().optional() });
778
+ const request$10 = {
779
+ params: z.object({ jobId: cuidSchema }),
780
+ body: z.object({
781
+ checkpoint: requestCheckpointSchema,
782
+ step: stepSchema
783
+ })
784
+ };
785
+ const response$11 = z.object({ data: z.object({ checkpoint: apiCheckpointSchema }) });
786
+
787
+ //#endregion
788
+ //#region ../models/src/api/jobs/checkpoints/get.ts
789
+ const request$9 = { params: z.object({
790
+ jobId: cuidSchema,
791
+ checkpointId: cuidSchema
792
+ }) };
793
+ const response$10 = z.object({ data: z.object({ checkpoint: apiCheckpointSchema }) });
794
+
795
+ //#endregion
796
+ //#region ../models/src/api/jobs/checkpoints/getAll.ts
797
+ const request$8 = {
798
+ params: z.object({ jobId: cuidSchema }),
799
+ query: z.object({
800
+ filter: z.string().min(1).max(256).optional(),
801
+ sort: z.enum(["createdAt", "updatedAt"]).optional(),
802
+ order: z.enum(["asc", "desc"]).optional(),
803
+ take: z.coerce.number().min(1).max(100).default(10),
804
+ skip: z.coerce.number().min(0).default(0)
805
+ })
806
+ };
807
+ const response$9 = z.object({
808
+ data: z.object({ checkpoints: z.array(apiCheckpointSchema) }),
809
+ meta: paginationMeta
810
+ });
811
+
812
+ //#endregion
813
+ //#region ../models/src/api/jobs/checkpoints/stream.ts
814
+ const request$7 = { params: z.object({ jobId: cuidSchema }) };
815
+ const response$8 = z.object({ data: apiCheckpointSchema });
816
+
817
+ //#endregion
818
+ //#region ../support-models/src/index.ts
819
+ const anthropicSupportModels = [
820
+ {
821
+ modelId: "claude-opus-4-5",
822
+ default: false,
823
+ provider: "anthropic",
824
+ contextWindow: 2e5
825
+ },
826
+ {
827
+ modelId: "claude-opus-4-1",
828
+ default: false,
829
+ provider: "anthropic",
830
+ contextWindow: 2e5
831
+ },
832
+ {
833
+ modelId: "claude-opus-4-20250514",
834
+ default: false,
835
+ provider: "anthropic",
836
+ contextWindow: 2e5
837
+ },
838
+ {
839
+ modelId: "claude-sonnet-4-5",
840
+ default: true,
841
+ provider: "anthropic",
842
+ contextWindow: 2e5
843
+ },
844
+ {
845
+ modelId: "claude-sonnet-4-20250514",
846
+ default: false,
847
+ provider: "anthropic",
848
+ contextWindow: 2e5
849
+ },
850
+ {
851
+ modelId: "claude-3-7-sonnet-20250219",
852
+ default: false,
853
+ provider: "anthropic",
854
+ contextWindow: 2e5
855
+ },
856
+ {
857
+ modelId: "claude-haiku-4-5",
858
+ default: false,
859
+ provider: "anthropic",
860
+ contextWindow: 2e5
861
+ },
862
+ {
863
+ modelId: "claude-3-5-haiku-latest",
864
+ default: false,
865
+ provider: "anthropic",
866
+ contextWindow: 2e5
867
+ }
868
+ ];
869
+ const googleSupportModels = [
870
+ {
871
+ modelId: "gemini-3-pro-preview",
872
+ default: false,
873
+ provider: "google",
874
+ contextWindow: 1e6
875
+ },
876
+ {
877
+ modelId: "gemini-2.5-pro",
878
+ default: true,
879
+ provider: "google",
880
+ contextWindow: 1e6
881
+ },
882
+ {
883
+ modelId: "gemini-2.5-flash",
884
+ default: false,
885
+ provider: "google",
886
+ contextWindow: 1e6
887
+ },
888
+ {
889
+ modelId: "gemini-2.5-flash-lite",
890
+ default: false,
891
+ provider: "google",
892
+ contextWindow: 1e6
893
+ }
894
+ ];
895
+ const openAiSupportModels = [
896
+ {
897
+ modelId: "gpt-5",
898
+ default: true,
899
+ provider: "openai",
900
+ contextWindow: 4e5
901
+ },
902
+ {
903
+ modelId: "gpt-5-mini",
904
+ default: false,
905
+ provider: "openai",
906
+ contextWindow: 4e5
907
+ },
908
+ {
909
+ modelId: "gpt-5-nano",
910
+ default: false,
911
+ provider: "openai",
912
+ contextWindow: 4e5
913
+ },
914
+ {
915
+ modelId: "gpt-5-chat-latest",
916
+ default: false,
917
+ provider: "openai",
918
+ contextWindow: 128e3
919
+ },
920
+ {
921
+ modelId: "o4-mini",
922
+ default: false,
923
+ provider: "openai",
924
+ contextWindow: 2e5
925
+ },
926
+ {
927
+ modelId: "o3",
928
+ default: false,
929
+ provider: "openai",
930
+ contextWindow: 2e5
931
+ },
932
+ {
933
+ modelId: "o3-mini",
934
+ default: false,
935
+ provider: "openai",
936
+ contextWindow: 2e5
937
+ },
938
+ {
939
+ modelId: "gpt-4.1",
940
+ default: false,
941
+ provider: "openai",
942
+ contextWindow: 1e6
943
+ }
944
+ ];
945
+ const deepseekSupportModels = [{
946
+ modelId: "deepseek-chat",
947
+ default: true,
948
+ provider: "deepseek",
949
+ contextWindow: 128e3
950
+ }, {
951
+ modelId: "deepseek-reasoner",
952
+ default: false,
953
+ provider: "deepseek",
954
+ contextWindow: 128e3
955
+ }];
956
+ const allSupportModels = [
957
+ ...anthropicSupportModels,
958
+ ...googleSupportModels,
959
+ ...openAiSupportModels,
960
+ ...deepseekSupportModels
961
+ ];
962
+ const supportModels = Object.fromEntries(allSupportModels.map((model) => [model.modelId, model]));
963
+ function getSupportModelNames() {
964
+ return Object.keys(supportModels);
965
+ }
966
+
967
+ //#endregion
968
+ //#region ../models/src/domain/job.ts
969
+ const reasoningBudgetSchema = z.union([z.enum([
970
+ "none",
971
+ "minimal",
972
+ "low",
973
+ "medium",
974
+ "high"
975
+ ]), z.number().min(0)]);
976
+ const jobStatusSchema = z.enum([
977
+ "queued",
978
+ "processing",
979
+ "completed",
980
+ "requestInteractiveToolResult",
981
+ "requestDelegateResult",
982
+ "exceededMaxSteps",
983
+ "failed",
984
+ "canceling",
985
+ "canceled",
986
+ "expired"
987
+ ]);
988
+ const modelNames = getSupportModelNames();
989
+ const firstModel = modelNames[0];
990
+ if (firstModel === void 0) throw new Error("No support models available");
991
+ const modelEnum = z.enum([firstModel, ...modelNames.slice(1)]);
992
+ const jobSchema = z.object({
993
+ type: z.literal("job"),
994
+ id: cuidSchema,
995
+ organizationId: cuidSchema,
996
+ applicationId: cuidSchema,
997
+ createdAt: datetimeSchema,
998
+ updatedAt: datetimeSchema,
999
+ status: jobStatusSchema,
1000
+ coordinatorExpertKey: expertKeyFieldSchema,
1001
+ query: z.string().min(1).max(maxExpertJobQueryLength).optional(),
1002
+ files: z.array(z.string().min(1).max(maxExpertJobFileNameLength)),
1003
+ expert: expertWithMetadataSchema,
1004
+ provider: providerSchema,
1005
+ model: modelEnum,
1006
+ reasoningBudget: reasoningBudgetSchema,
1007
+ maxSteps: z.number().int().min(1),
1008
+ maxRetries: z.number().int().min(0),
1009
+ currentStep: z.number().int().min(0),
1010
+ totalSteps: z.number().int().min(0),
1011
+ totalDuration: z.number().min(0),
1012
+ usage: usageSchema
1013
+ });
1014
+
1015
+ //#endregion
1016
+ //#region ../models/src/api/jobs/continue.ts
1017
+ const request$6 = {
1018
+ params: z.object({ jobId: cuidSchema }),
1019
+ body: z.object({
1020
+ query: jobSchema.shape.query.optional(),
1021
+ interactiveToolCallResult: z.boolean().optional(),
1022
+ files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).optional(),
1023
+ provider: providerSchema.optional(),
1024
+ model: jobSchema.shape.model.optional(),
1025
+ reasoningBudget: reasoningBudgetSchema.optional(),
1026
+ maxSteps: z.coerce.number().optional(),
1027
+ maxRetries: z.coerce.number().optional()
1028
+ })
1029
+ };
1030
+ const response$7 = z.object({ data: z.object({ job: jobSchema }) });
1031
+
1032
+ //#endregion
1033
+ //#region ../models/src/api/jobs/create.ts
1034
+ const request$5 = { body: z.object({
1035
+ applicationId: cuidSchema.describe("Application ID to create the job in"),
1036
+ expertKey: expertKeyFieldSchema,
1037
+ query: jobSchema.shape.query.optional(),
1038
+ files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).optional(),
1039
+ provider: providerSchema,
1040
+ model: jobSchema.shape.model.optional(),
1041
+ reasoningBudget: reasoningBudgetSchema.optional(),
1042
+ maxSteps: z.coerce.number().optional(),
1043
+ maxRetries: z.coerce.number().optional()
1044
+ }) };
1045
+ const response$6 = z.object({ data: z.object({ job: jobSchema }) });
1046
+
1047
+ //#endregion
1048
+ //#region ../models/src/api/jobs/get.ts
1049
+ const request$4 = { params: z.object({ jobId: cuidSchema }) };
1050
+ const response$5 = z.object({ data: z.object({ job: jobSchema }) });
1051
+
1052
+ //#endregion
1053
+ //#region ../models/src/api/jobs/getAll.ts
1054
+ const request$3 = { query: z.object({
1055
+ sort: z.enum(["createdAt", "updatedAt"]).optional(),
1056
+ order: z.enum(["asc", "desc"]).optional(),
1057
+ take: z.coerce.number().min(1).max(100).default(100),
1058
+ skip: z.coerce.number().min(0).default(0)
1059
+ }) };
1060
+ const response$4 = z.object({
1061
+ data: z.object({ jobs: z.array(jobSchema) }),
1062
+ meta: paginationMeta
1063
+ });
1064
+
1065
+ //#endregion
1066
+ //#region ../models/src/api/jobs/update.ts
1067
+ const request$2 = {
1068
+ params: z.object({ jobId: cuidSchema }),
1069
+ body: z.object({ status: jobStatusSchema })
1070
+ };
1071
+ const response$3 = z.object({ data: z.object({ job: jobSchema }) });
1072
+
1073
+ //#endregion
1074
+ //#region ../models/src/api/jobs/workspace/get.ts
1075
+ const workspaceCommitSchema = z.object({
1076
+ sha: z.string(),
1077
+ message: z.string(),
1078
+ author: z.string(),
1079
+ timestamp: z.string()
1080
+ });
1081
+ const workspaceStatsSchema = z.object({
1082
+ commits: z.number().int().min(0),
1083
+ filesChanged: z.number().int().min(0),
1084
+ additions: z.number().int().min(0),
1085
+ deletions: z.number().int().min(0)
1086
+ });
1087
+ const workspaceSchema = z.object({
1088
+ jobId: z.string(),
1089
+ branch: z.string(),
1090
+ baseBranch: z.string(),
1091
+ lastCommit: workspaceCommitSchema.optional(),
1092
+ stats: workspaceStatsSchema.optional()
1093
+ });
1094
+ const request$1 = { params: z.object({ jobId: cuidSchema }) };
1095
+ const response$2 = z.object({ data: z.object({ workspace: workspaceSchema }) });
1096
+
1097
+ //#endregion
1098
+ //#region ../models/src/api/jobs/workspace/tree.ts
1099
+ const workspaceItemSchema = z.object({
1100
+ type: z.enum(["directory", "file"]),
1101
+ path: z.string(),
1102
+ name: z.string(),
1103
+ size: z.number().optional(),
1104
+ sha: z.string().optional()
1105
+ });
1106
+ const request = {
1107
+ params: z.object({ jobId: cuidSchema }),
1108
+ query: z.object({
1109
+ path: z.string().optional(),
1110
+ recursive: z.coerce.boolean().optional()
1111
+ })
1112
+ };
1113
+ const response$1 = z.object({ data: z.object({ items: z.array(workspaceItemSchema) }) });
1114
+
1115
+ //#endregion
1116
+ //#region ../models/src/domain/user.ts
1117
+ const userStatusSchema = z.enum([
1118
+ "active",
1119
+ "inactive",
1120
+ "deleted"
1121
+ ]);
1122
+ const userSchema = z.object({
1123
+ type: z.literal("user"),
1124
+ id: cuidSchema,
1125
+ email: z.string().email(),
1126
+ emailVerified: z.boolean(),
1127
+ name: z.string().min(1).max(255).optional(),
1128
+ image: z.string().url().optional(),
1129
+ status: userStatusSchema,
1130
+ organizations: z.array(organizationSchema),
1131
+ createdAt: datetimeSchema,
1132
+ updatedAt: datetimeSchema
1133
+ });
1134
+
1135
+ //#endregion
1136
+ //#region ../models/src/api/session/get.ts
1137
+ const response = z.object({ data: z.object({
1138
+ user: userSchema,
1139
+ organization: organizationSchema,
1140
+ application: applicationSchema.nullable()
1141
+ }) });
1142
+
1143
+ //#endregion
1144
+ //#region ../models/src/domain/apiKey.ts
1145
+ const apiKeyPermissionsSchema = z.object({
1146
+ operations: z.array(z.string()),
1147
+ experts: z.union([z.array(z.string()), z.literal("*")]).optional()
1148
+ });
1149
+ const apiKeySchema = z.object({
1150
+ type: z.literal("apiKey"),
1151
+ id: cuidSchema,
1152
+ name: z.string().min(1).max(255).optional(),
1153
+ start: z.string().optional(),
1154
+ prefix: z.string().optional(),
1155
+ user: userSchema.optional(),
1156
+ enabled: z.boolean(),
1157
+ expiresAt: datetimeSchema.optional(),
1158
+ permissions: apiKeyPermissionsSchema.optional(),
1159
+ lastRequest: datetimeSchema.optional(),
1160
+ createdAt: datetimeSchema,
1161
+ updatedAt: datetimeSchema
1162
+ });
1163
+ const createApiKeyInputSchema = z.object({
1164
+ name: z.string().min(1).max(255).optional(),
1165
+ organizationId: cuidSchema,
1166
+ operations: z.array(z.string()).optional(),
1167
+ experts: z.union([z.array(z.string()), z.literal("*")]).optional(),
1168
+ expiresIn: z.number().min(60).optional()
1169
+ });
1170
+ const createApiKeyResponseSchema = z.object({
1171
+ apiKey: apiKeySchema,
1172
+ key: z.string()
1173
+ });
1174
+
1175
+ //#endregion
1176
+ //#region ../models/src/domain/providerSetting.ts
1177
+ const baseUrlSchema = z.string().url().max(maxProviderBaseUrlLength).optional();
1178
+ const headersSchema = z.record(z.string().min(1).max(maxProviderHeaderKeyLength), z.string().max(maxProviderHeaderValueLength)).refine((headers) => Object.keys(headers).length <= maxProviderHeadersCount, { message: `Headers must have at most ${maxProviderHeadersCount} entries` }).optional();
1179
+ const anthropicProviderSettingsSchema = z.object({
1180
+ baseUrl: baseUrlSchema,
1181
+ headers: headersSchema
1182
+ });
1183
+ const googleProviderSettingsSchema = z.object({
1184
+ baseUrl: baseUrlSchema,
1185
+ headers: headersSchema
1186
+ });
1187
+ const openaiProviderSettingsSchema = z.object({
1188
+ baseUrl: baseUrlSchema,
1189
+ headers: headersSchema,
1190
+ organization: z.string().optional(),
1191
+ project: z.string().optional(),
1192
+ name: z.string().optional()
1193
+ });
1194
+ const deepseekProviderSettingsSchema = z.object({
1195
+ baseUrl: baseUrlSchema,
1196
+ headers: headersSchema
1197
+ });
1198
+ const azureOpenaiProviderSettingsSchema = z.object({
1199
+ baseUrl: baseUrlSchema,
1200
+ headers: headersSchema,
1201
+ resourceName: z.string().optional(),
1202
+ apiVersion: z.string().optional(),
1203
+ useDeploymentBasedUrls: z.boolean().optional()
1204
+ });
1205
+ const amazonBedrockProviderSettingsSchema = z.object({ region: z.string().optional() });
1206
+ const googleVertexProviderSettingsSchema = z.object({
1207
+ baseUrl: baseUrlSchema,
1208
+ headers: headersSchema,
1209
+ project: z.string().optional(),
1210
+ location: z.string().optional()
1211
+ });
1212
+ const providerSettingsSchema = z.union([
1213
+ anthropicProviderSettingsSchema,
1214
+ googleProviderSettingsSchema,
1215
+ openaiProviderSettingsSchema,
1216
+ deepseekProviderSettingsSchema,
1217
+ azureOpenaiProviderSettingsSchema,
1218
+ amazonBedrockProviderSettingsSchema,
1219
+ googleVertexProviderSettingsSchema
1220
+ ]);
1221
+ const providerSettingSchema = z.object({
1222
+ type: z.literal("providerSetting"),
1223
+ id: cuidSchema,
1224
+ applicationId: cuidSchema,
1225
+ provider: providerSchema,
1226
+ settings: providerSettingsSchema.optional(),
1227
+ application: applicationSchema,
1228
+ createdAt: datetimeSchema,
1229
+ updatedAt: datetimeSchema
1230
+ });
1231
+
1232
+ //#endregion
1233
+ //#region ../models/src/domain/providerApiKey.ts
1234
+ const providerApiKeyNameSchema = z.string().min(1).max(255);
1235
+ const providerApiKeyValueSchema = z.string().min(1);
1236
+ const providerApiKeySchema = z.object({
1237
+ type: z.literal("providerApiKey"),
1238
+ id: cuidSchema,
1239
+ providerSettingId: cuidSchema,
1240
+ name: providerApiKeyNameSchema,
1241
+ lastUsedAt: datetimeSchema.optional(),
1242
+ expiresAt: datetimeSchema.optional(),
1243
+ providerSetting: providerSettingSchema,
1244
+ createdAt: datetimeSchema,
1245
+ updatedAt: datetimeSchema
1246
+ });
1247
+
1248
+ //#endregion
1249
+ //#region ../models/src/domain/run.ts
1250
+ const runStatusSchema = z.enum([
1251
+ "queued",
1252
+ "processing",
1253
+ "completed",
1254
+ "stoppedByInteractiveTool",
1255
+ "stoppedByDelegate",
1256
+ "stoppedByExceededMaxSteps",
1257
+ "stoppedByError"
1258
+ ]);
1259
+ const runSchema = z.object({
1260
+ type: z.literal("run"),
1261
+ id: cuidSchema,
1262
+ jobId: cuidSchema,
1263
+ parentRunId: cuidSchema.optional(),
1264
+ organizationId: cuidSchema,
1265
+ createdAt: datetimeSchema,
1266
+ updatedAt: datetimeSchema,
1267
+ status: runStatusSchema,
1268
+ runtimeVersion: runtimeVersionSchema,
1269
+ expertKey: expertKeyFieldSchema,
1270
+ interactiveToolCallResult: z.boolean().optional(),
1271
+ expert: expertWithMetadataSchema,
1272
+ stepNumber: z.number().int().min(0),
1273
+ usage: usageSchema,
1274
+ machineId: z.string().optional()
1275
+ });
1276
+
1277
+ //#endregion
1278
+ //#region src/lib/errors.ts
1279
+ function createValidationError(error) {
1280
+ return {
1281
+ code: 400,
1282
+ message: `Validation failed: ${error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`,
1283
+ reason: error.issues
1284
+ };
1285
+ }
1286
+ function createAbortError() {
1287
+ return {
1288
+ code: 0,
1289
+ message: "Request aborted",
1290
+ aborted: true
1291
+ };
1292
+ }
1293
+ function createNetworkError(error) {
1294
+ return {
1295
+ code: 0,
1296
+ message: error instanceof Error ? error.message : "Network error",
1297
+ reason: error
1298
+ };
1299
+ }
1300
+ function createHttpError(status, statusText, body) {
1301
+ if (typeof body === "object" && body !== null) {
1302
+ const hasReason = "reason" in body;
1303
+ if ("error" in body && typeof body.error === "string") return {
1304
+ code: status,
1305
+ message: body.error,
1306
+ reason: hasReason ? body.reason : void 0
1307
+ };
1308
+ if (hasReason) return {
1309
+ code: status,
1310
+ message: statusText,
1311
+ reason: body.reason
1312
+ };
1313
+ }
1314
+ return {
1315
+ code: status,
1316
+ message: statusText
1317
+ };
1318
+ }
1319
+
1320
+ //#endregion
1321
+ //#region src/endpoints/applications.ts
1322
+ const BASE_PATH$4 = "/api/v1/applications";
1323
+ function buildQueryString$4(params) {
1324
+ if (!params) return "";
1325
+ const searchParams = new URLSearchParams();
1326
+ if (params.name !== void 0) searchParams.set("name", params.name);
1327
+ if (params.sort !== void 0) searchParams.set("sort", params.sort);
1328
+ if (params.order !== void 0) searchParams.set("order", params.order);
1329
+ if (params.take !== void 0) searchParams.set("take", params.take.toString());
1330
+ if (params.skip !== void 0) searchParams.set("skip", params.skip.toString());
1331
+ const queryString = searchParams.toString();
1332
+ return queryString ? `?${queryString}` : "";
1333
+ }
1334
+ function createApplicationsApi(fetcher) {
1335
+ return {
1336
+ async list(params, options) {
1337
+ if (params) {
1338
+ const result = request$35.query.safeParse(params);
1339
+ if (!result.success) return {
1340
+ ok: false,
1341
+ error: createValidationError(result.error)
1342
+ };
1343
+ }
1344
+ const queryString = buildQueryString$4(params);
1345
+ return fetcher.get(`${BASE_PATH$4}${queryString}`, options);
1346
+ },
1347
+ async get(id, options) {
1348
+ return fetcher.get(`${BASE_PATH$4}/${id}`, options);
1349
+ },
1350
+ async create(input, options) {
1351
+ const result = request$38.body.safeParse(input);
1352
+ if (!result.success) return {
1353
+ ok: false,
1354
+ error: createValidationError(result.error)
1355
+ };
1356
+ return fetcher.post(BASE_PATH$4, input, options);
1357
+ },
1358
+ async update(id, input, options) {
1359
+ const result = request$34.body.safeParse(input);
1360
+ if (!result.success) return {
1361
+ ok: false,
1362
+ error: createValidationError(result.error)
1363
+ };
1364
+ return fetcher.post(`${BASE_PATH$4}/${id}`, input, options);
1365
+ },
1366
+ async delete(id, options) {
1367
+ return fetcher.delete(`${BASE_PATH$4}/${id}`, options);
1368
+ }
1369
+ };
1370
+ }
1371
+
1372
+ //#endregion
1373
+ //#region src/endpoints/env-secrets.ts
1374
+ const BASE_PATH$3 = "/api/v1/env/secrets";
1375
+ function createSecretsApi(fetcher) {
1376
+ return {
1377
+ async list(options) {
1378
+ return fetcher.get(BASE_PATH$3, options);
1379
+ },
1380
+ async get(name, options) {
1381
+ const encodedName = encodeURIComponent(name);
1382
+ return fetcher.get(`${BASE_PATH$3}/${encodedName}`, options);
1383
+ },
1384
+ async create(input, options) {
1385
+ const result = request$33.body.safeParse(input);
1386
+ if (!result.success) return {
1387
+ ok: false,
1388
+ error: createValidationError(result.error)
1389
+ };
1390
+ return fetcher.post(BASE_PATH$3, input, options);
1391
+ },
1392
+ async update(name, input, options) {
1393
+ const result = request$29.body.safeParse(input);
1394
+ if (!result.success) return {
1395
+ ok: false,
1396
+ error: createValidationError(result.error)
1397
+ };
1398
+ const encodedName = encodeURIComponent(name);
1399
+ return fetcher.put(`${BASE_PATH$3}/${encodedName}`, input, options);
1400
+ },
1401
+ async delete(name, options) {
1402
+ const encodedName = encodeURIComponent(name);
1403
+ return fetcher.deleteNoContent(`${BASE_PATH$3}/${encodedName}`, options);
1404
+ }
1405
+ };
1406
+ }
1407
+
1408
+ //#endregion
1409
+ //#region src/endpoints/env-variables.ts
1410
+ const BASE_PATH$2 = "/api/v1/env/variables";
1411
+ function createVariablesApi(fetcher) {
1412
+ return {
1413
+ async list(options) {
1414
+ return fetcher.get(BASE_PATH$2, options);
1415
+ },
1416
+ async get(name, options) {
1417
+ const encodedName = encodeURIComponent(name);
1418
+ return fetcher.get(`${BASE_PATH$2}/${encodedName}`, options);
1419
+ },
1420
+ async create(input, options) {
1421
+ const result = request$28.body.safeParse(input);
1422
+ if (!result.success) return {
1423
+ ok: false,
1424
+ error: createValidationError(result.error)
1425
+ };
1426
+ return fetcher.post(BASE_PATH$2, input, options);
1427
+ },
1428
+ async update(name, input, options) {
1429
+ const result = request$24.body.safeParse(input);
1430
+ if (!result.success) return {
1431
+ ok: false,
1432
+ error: createValidationError(result.error)
1433
+ };
1434
+ const encodedName = encodeURIComponent(name);
1435
+ return fetcher.put(`${BASE_PATH$2}/${encodedName}`, input, options);
1436
+ },
1437
+ async delete(name, options) {
1438
+ const encodedName = encodeURIComponent(name);
1439
+ return fetcher.deleteNoContent(`${BASE_PATH$2}/${encodedName}`, options);
1440
+ }
1441
+ };
1442
+ }
1443
+
1444
+ //#endregion
1445
+ //#region src/endpoints/env.ts
1446
+ function createEnvApi(fetcher) {
1447
+ return {
1448
+ secrets: createSecretsApi(fetcher),
1449
+ variables: createVariablesApi(fetcher)
1450
+ };
1451
+ }
1452
+
1453
+ //#endregion
1454
+ //#region src/endpoints/experts-drafts.ts
1455
+ function buildQueryString$3(params) {
1456
+ if (!params) return "";
1457
+ const searchParams = new URLSearchParams();
1458
+ if (params.limit !== void 0) searchParams.set("limit", params.limit.toString());
1459
+ if (params.offset !== void 0) searchParams.set("offset", params.offset.toString());
1460
+ const queryString = searchParams.toString();
1461
+ return queryString ? `?${queryString}` : "";
1462
+ }
1463
+ function createDraftsApi(fetcher, basePath) {
1464
+ return {
1465
+ async list(scopeName, params, options) {
1466
+ if (params) {
1467
+ const result = request$19.query.safeParse(params);
1468
+ if (!result.success) return {
1469
+ ok: false,
1470
+ error: createValidationError(result.error)
1471
+ };
1472
+ }
1473
+ const encodedScopeName = encodeURIComponent(scopeName);
1474
+ const queryString = buildQueryString$3(params);
1475
+ return fetcher.get(`${basePath}/${encodedScopeName}/drafts${queryString}`, options);
1476
+ },
1477
+ async get(scopeName, draftRef, options) {
1478
+ const encodedScopeName = encodeURIComponent(scopeName);
1479
+ const encodedDraftRef = encodeURIComponent(draftRef);
1480
+ return fetcher.get(`${basePath}/${encodedScopeName}/drafts/${encodedDraftRef}`, options);
1481
+ },
1482
+ async create(scopeName, input, options) {
1483
+ const result = request$22.body.safeParse(input);
1484
+ if (!result.success) return {
1485
+ ok: false,
1486
+ error: createValidationError(result.error)
1487
+ };
1488
+ const encodedScopeName = encodeURIComponent(scopeName);
1489
+ return fetcher.post(`${basePath}/${encodedScopeName}/drafts`, input, options);
1490
+ },
1491
+ async update(scopeName, draftRef, input, options) {
1492
+ const result = request$18.body.safeParse(input);
1493
+ if (!result.success) return {
1494
+ ok: false,
1495
+ error: createValidationError(result.error)
1496
+ };
1497
+ const encodedScopeName = encodeURIComponent(scopeName);
1498
+ const encodedDraftRef = encodeURIComponent(draftRef);
1499
+ return fetcher.post(`${basePath}/${encodedScopeName}/drafts/${encodedDraftRef}`, input, options);
1500
+ },
1501
+ async delete(scopeName, draftRef, options) {
1502
+ const encodedScopeName = encodeURIComponent(scopeName);
1503
+ const encodedDraftRef = encodeURIComponent(draftRef);
1504
+ return fetcher.delete(`${basePath}/${encodedScopeName}/drafts/${encodedDraftRef}`, options);
1505
+ },
1506
+ async assignVersion(scopeName, draftRef, input, options) {
1507
+ const result = request$17.body.safeParse(input);
1508
+ if (!result.success) return {
1509
+ ok: false,
1510
+ error: createValidationError(result.error)
1511
+ };
1512
+ const encodedScopeName = encodeURIComponent(scopeName);
1513
+ const encodedDraftRef = encodeURIComponent(draftRef);
1514
+ return fetcher.post(`${basePath}/${encodedScopeName}/drafts/${encodedDraftRef}/version`, input, options);
1515
+ }
1516
+ };
1517
+ }
1518
+
1519
+ //#endregion
1520
+ //#region src/endpoints/experts-versions.ts
1521
+ function createVersionsApi(fetcher, basePath) {
1522
+ return { async list(scopeName, options) {
1523
+ const encodedScopeName = encodeURIComponent(scopeName);
1524
+ return fetcher.get(`${basePath}/${encodedScopeName}/versions`, options);
1525
+ } };
1526
+ }
1527
+
1528
+ //#endregion
1529
+ //#region src/endpoints/experts.ts
1530
+ const BASE_PATH$1 = "/api/v1/experts";
1531
+ function buildQueryString$2(params) {
1532
+ if (!params) return "";
1533
+ const searchParams = new URLSearchParams();
1534
+ if (params.filter !== void 0) searchParams.set("filter", params.filter);
1535
+ if (params.category !== void 0) searchParams.set("category", params.category);
1536
+ if (params.includeDrafts !== void 0) searchParams.set("includeDrafts", params.includeDrafts.toString());
1537
+ if (params.limit !== void 0) searchParams.set("limit", params.limit.toString());
1538
+ if (params.offset !== void 0) searchParams.set("offset", params.offset.toString());
1539
+ const queryString = searchParams.toString();
1540
+ return queryString ? `?${queryString}` : "";
1541
+ }
1542
+ function createExpertsApi(fetcher) {
1543
+ return {
1544
+ async list(params, options) {
1545
+ if (params) {
1546
+ const result = request$15.query.safeParse(params);
1547
+ if (!result.success) return {
1548
+ ok: false,
1549
+ error: createValidationError(result.error)
1550
+ };
1551
+ }
1552
+ const queryString = buildQueryString$2(params);
1553
+ return fetcher.get(`${BASE_PATH$1}${queryString}`, options);
1554
+ },
1555
+ async get(key, options) {
1556
+ const encodedKey = encodeURIComponent(key);
1557
+ return fetcher.get(`${BASE_PATH$1}/${encodedKey}`, options);
1558
+ },
1559
+ async getFeatured(options) {
1560
+ return fetcher.get(`${BASE_PATH$1}/featured`, options);
1561
+ },
1562
+ async getMeta(key, options) {
1563
+ const encodedKey = encodeURIComponent(key);
1564
+ return fetcher.get(`${BASE_PATH$1}/${encodedKey}/meta`, options);
1565
+ },
1566
+ async publish(scopeName, options) {
1567
+ const encodedScopeName = encodeURIComponent(scopeName);
1568
+ return fetcher.post(`${BASE_PATH$1}/${encodedScopeName}/publish`, {}, options);
1569
+ },
1570
+ async unpublish(scopeName, options) {
1571
+ const encodedScopeName = encodeURIComponent(scopeName);
1572
+ return fetcher.post(`${BASE_PATH$1}/${encodedScopeName}/unpublish`, {}, options);
1573
+ },
1574
+ async yank(key, options) {
1575
+ const encodedKey = encodeURIComponent(key);
1576
+ return fetcher.delete(`${BASE_PATH$1}/${encodedKey}`, options);
1577
+ },
1578
+ drafts: createDraftsApi(fetcher, BASE_PATH$1),
1579
+ versions: createVersionsApi(fetcher, BASE_PATH$1)
1580
+ };
1581
+ }
1582
+
1583
+ //#endregion
1584
+ //#region src/lib/sse.ts
1585
+ async function* parseSSE(reader) {
1586
+ const decoder = new TextDecoder();
1587
+ let buffer = "";
1588
+ while (true) {
1589
+ const { value, done } = await reader.read();
1590
+ if (done) break;
1591
+ buffer += decoder.decode(value, { stream: true });
1592
+ const events = buffer.split("\n\n");
1593
+ buffer = events.pop() || "";
1594
+ for (const event of events) {
1595
+ if (event.trim() === "") continue;
1596
+ const lines = event.split("\n");
1597
+ const eventType = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
1598
+ const data = lines.find((line) => line.startsWith("data:"))?.slice(5).trim();
1599
+ if (eventType !== "message" || !data) continue;
1600
+ try {
1601
+ yield JSON.parse(data);
1602
+ } catch {}
1603
+ }
1604
+ }
1605
+ }
1606
+
1607
+ //#endregion
1608
+ //#region src/endpoints/jobs-checkpoints.ts
1609
+ function buildQueryString$1(params) {
1610
+ if (!params) return "";
1611
+ const searchParams = new URLSearchParams();
1612
+ if (params.take !== void 0) searchParams.set("take", params.take.toString());
1613
+ if (params.skip !== void 0) searchParams.set("skip", params.skip.toString());
1614
+ if (params.sort !== void 0) searchParams.set("sort", params.sort);
1615
+ if (params.order !== void 0) searchParams.set("order", params.order);
1616
+ const queryString = searchParams.toString();
1617
+ return queryString ? `?${queryString}` : "";
1618
+ }
1619
+ function createCheckpointsApi(fetcher, basePath) {
1620
+ return {
1621
+ async list(jobId, params, options) {
1622
+ if (params) {
1623
+ const result = request$8.query.safeParse(params);
1624
+ if (!result.success) return {
1625
+ ok: false,
1626
+ error: createValidationError(result.error)
1627
+ };
1628
+ }
1629
+ const queryString = buildQueryString$1(params);
1630
+ return fetcher.get(`${basePath}/${jobId}/checkpoints${queryString}`, options);
1631
+ },
1632
+ async get(jobId, checkpointId, options) {
1633
+ return fetcher.get(`${basePath}/${jobId}/checkpoints/${checkpointId}`, options);
1634
+ },
1635
+ async create(jobId, input, options) {
1636
+ const result = request$10.body.safeParse(input);
1637
+ if (!result.success) return {
1638
+ ok: false,
1639
+ error: createValidationError(result.error)
1640
+ };
1641
+ return fetcher.post(`${basePath}/${jobId}/checkpoints`, input, options);
1642
+ },
1643
+ async *stream(jobId, options) {
1644
+ const result = await fetcher.getStream(`${basePath}/${jobId}/checkpoints/stream`, options);
1645
+ if (!result.ok) throw new Error(`Failed to start checkpoint stream: ${result.error.message}`);
1646
+ const reader = result.data.getReader();
1647
+ for await (const checkpoint of parseSSE(reader)) yield checkpoint;
1648
+ }
1649
+ };
1650
+ }
1651
+
1652
+ //#endregion
1653
+ //#region src/endpoints/jobs-workspace.ts
1654
+ function buildTreeQueryString(params) {
1655
+ if (!params) return "";
1656
+ const searchParams = new URLSearchParams();
1657
+ if (params.path !== void 0) searchParams.set("path", params.path);
1658
+ if (params.recursive !== void 0) searchParams.set("recursive", params.recursive.toString());
1659
+ const queryString = searchParams.toString();
1660
+ return queryString ? `?${queryString}` : "";
1661
+ }
1662
+ function createWorkspaceApi(fetcher, basePath) {
1663
+ return {
1664
+ async get(jobId, options) {
1665
+ return fetcher.get(`${basePath}/${jobId}/workspace`, options);
1666
+ },
1667
+ async tree(jobId, params, options) {
1668
+ if (params) {
1669
+ const result = request.query.safeParse(params);
1670
+ if (!result.success) return {
1671
+ ok: false,
1672
+ error: createValidationError(result.error)
1673
+ };
1674
+ }
1675
+ const queryString = buildTreeQueryString(params);
1676
+ return fetcher.get(`${basePath}/${jobId}/workspace/tree${queryString}`, options);
1677
+ },
1678
+ async blob(jobId, path, options) {
1679
+ const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
1680
+ return fetcher.getBlob(`${basePath}/${jobId}/workspace/blob/${normalizedPath}`, options);
1681
+ }
1682
+ };
1683
+ }
1684
+
1685
+ //#endregion
1686
+ //#region src/endpoints/jobs.ts
1687
+ const BASE_PATH = "/api/v1/jobs";
1688
+ function buildQueryString(params) {
1689
+ if (!params) return "";
1690
+ const searchParams = new URLSearchParams();
1691
+ if (params.take !== void 0) searchParams.set("take", params.take.toString());
1692
+ if (params.skip !== void 0) searchParams.set("skip", params.skip.toString());
1693
+ if (params.sort !== void 0) searchParams.set("sort", params.sort);
1694
+ if (params.order !== void 0) searchParams.set("order", params.order);
1695
+ const queryString = searchParams.toString();
1696
+ return queryString ? `?${queryString}` : "";
1697
+ }
1698
+ function createJobsApi(fetcher) {
1699
+ return {
1700
+ async list(params, options) {
1701
+ if (params) {
1702
+ const result = request$3.query.safeParse(params);
1703
+ if (!result.success) return {
1704
+ ok: false,
1705
+ error: createValidationError(result.error)
1706
+ };
1707
+ }
1708
+ const queryString = buildQueryString(params);
1709
+ return fetcher.get(`${BASE_PATH}${queryString}`, options);
1710
+ },
1711
+ async get(id, options) {
1712
+ return fetcher.get(`${BASE_PATH}/${id}`, options);
1713
+ },
1714
+ async start(input, options) {
1715
+ const result = request$5.body.safeParse(input);
1716
+ if (!result.success) return {
1717
+ ok: false,
1718
+ error: createValidationError(result.error)
1719
+ };
1720
+ return fetcher.post(BASE_PATH, input, options);
1721
+ },
1722
+ async update(id, input, options) {
1723
+ const result = request$2.body.safeParse(input);
1724
+ if (!result.success) return {
1725
+ ok: false,
1726
+ error: createValidationError(result.error)
1727
+ };
1728
+ return fetcher.post(`${BASE_PATH}/${id}`, input, options);
1729
+ },
1730
+ async continue(id, input, options) {
1731
+ const result = request$6.body.safeParse(input);
1732
+ if (!result.success) return {
1733
+ ok: false,
1734
+ error: createValidationError(result.error)
1735
+ };
1736
+ return fetcher.post(`${BASE_PATH}/${id}/continue`, input, options);
1737
+ },
1738
+ async cancel(id, options) {
1739
+ return fetcher.post(`${BASE_PATH}/${id}/cancel`, {}, options);
1740
+ },
1741
+ checkpoints: createCheckpointsApi(fetcher, BASE_PATH),
1742
+ workspace: createWorkspaceApi(fetcher, BASE_PATH)
1743
+ };
1744
+ }
1745
+
1746
+ //#endregion
1747
+ //#region src/lib/fetcher.ts
1748
+ const DEFAULT_BASE_URL = "https://api.perstack.ai";
1749
+ const DEFAULT_TIMEOUT = 3e4;
1750
+ function createFetcher(config) {
1751
+ const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
1752
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
1753
+ const useCredentials = "credentials" in config && config.credentials === "include";
1754
+ const apiKey = "apiKey" in config ? config.apiKey : void 0;
1755
+ function buildUrl(path) {
1756
+ return `${baseUrl}${path}`;
1757
+ }
1758
+ function buildHeaders() {
1759
+ const headers = { "Content-Type": "application/json" };
1760
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
1761
+ return headers;
1762
+ }
1763
+ function getCredentials() {
1764
+ return useCredentials ? "include" : void 0;
1765
+ }
1766
+ function createTimeoutSignal(externalSignal) {
1767
+ const controller = new AbortController();
1768
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1769
+ let abortHandler;
1770
+ if (externalSignal) if (externalSignal.aborted) controller.abort();
1771
+ else {
1772
+ abortHandler = () => controller.abort();
1773
+ externalSignal.addEventListener("abort", abortHandler);
1774
+ }
1775
+ return {
1776
+ signal: controller.signal,
1777
+ cleanup: () => {
1778
+ clearTimeout(timeoutId);
1779
+ if (abortHandler && externalSignal) externalSignal.removeEventListener("abort", abortHandler);
1780
+ }
1781
+ };
1782
+ }
1783
+ async function request$39(method, path, body, options) {
1784
+ const { signal, cleanup } = createTimeoutSignal(options?.signal);
1785
+ try {
1786
+ const response$41 = await fetch(buildUrl(path), {
1787
+ method,
1788
+ headers: buildHeaders(),
1789
+ body: body ? JSON.stringify(body) : void 0,
1790
+ signal,
1791
+ credentials: getCredentials()
1792
+ });
1793
+ if (!response$41.ok) {
1794
+ let errorBody;
1795
+ try {
1796
+ errorBody = await response$41.json();
1797
+ } catch {
1798
+ errorBody = void 0;
1799
+ }
1800
+ return {
1801
+ ok: false,
1802
+ error: createHttpError(response$41.status, response$41.statusText, errorBody)
1803
+ };
1804
+ }
1805
+ return {
1806
+ ok: true,
1807
+ data: await response$41.json()
1808
+ };
1809
+ } catch (error) {
1810
+ if (error instanceof Error && error.name === "AbortError") return {
1811
+ ok: false,
1812
+ error: createAbortError()
1813
+ };
1814
+ return {
1815
+ ok: false,
1816
+ error: createNetworkError(error)
1817
+ };
1818
+ } finally {
1819
+ cleanup();
1820
+ }
1821
+ }
1822
+ async function requestBlob(path, options) {
1823
+ const { signal, cleanup } = createTimeoutSignal(options?.signal);
1824
+ try {
1825
+ const response$41 = await fetch(buildUrl(path), {
1826
+ method: "GET",
1827
+ headers: buildHeaders(),
1828
+ signal,
1829
+ credentials: getCredentials()
1830
+ });
1831
+ if (!response$41.ok) {
1832
+ let errorBody;
1833
+ try {
1834
+ errorBody = await response$41.json();
1835
+ } catch {
1836
+ errorBody = void 0;
1837
+ }
1838
+ return {
1839
+ ok: false,
1840
+ error: createHttpError(response$41.status, response$41.statusText, errorBody)
1841
+ };
1842
+ }
1843
+ return {
1844
+ ok: true,
1845
+ data: await response$41.blob()
1846
+ };
1847
+ } catch (error) {
1848
+ if (error instanceof Error && error.name === "AbortError") return {
1849
+ ok: false,
1850
+ error: createAbortError()
1851
+ };
1852
+ return {
1853
+ ok: false,
1854
+ error: createNetworkError(error)
1855
+ };
1856
+ } finally {
1857
+ cleanup();
1858
+ }
1859
+ }
1860
+ async function requestStream(path, options) {
1861
+ const { signal, cleanup } = createTimeoutSignal(options?.signal);
1862
+ try {
1863
+ const response$41 = await fetch(buildUrl(path), {
1864
+ method: "GET",
1865
+ headers: buildHeaders(),
1866
+ signal,
1867
+ credentials: getCredentials()
1868
+ });
1869
+ if (!response$41.ok) {
1870
+ let errorBody;
1871
+ try {
1872
+ errorBody = await response$41.json();
1873
+ } catch {
1874
+ errorBody = void 0;
1875
+ }
1876
+ cleanup();
1877
+ return {
1878
+ ok: false,
1879
+ error: createHttpError(response$41.status, response$41.statusText, errorBody)
1880
+ };
1881
+ }
1882
+ if (!response$41.body) {
1883
+ cleanup();
1884
+ return {
1885
+ ok: false,
1886
+ error: createNetworkError(/* @__PURE__ */ new Error("Response body is null"))
1887
+ };
1888
+ }
1889
+ cleanup();
1890
+ return {
1891
+ ok: true,
1892
+ data: response$41.body
1893
+ };
1894
+ } catch (error) {
1895
+ cleanup();
1896
+ if (error instanceof Error && error.name === "AbortError") return {
1897
+ ok: false,
1898
+ error: createAbortError()
1899
+ };
1900
+ return {
1901
+ ok: false,
1902
+ error: createNetworkError(error)
1903
+ };
1904
+ }
1905
+ }
1906
+ async function requestNoContent(method, path, options) {
1907
+ const { signal, cleanup } = createTimeoutSignal(options?.signal);
1908
+ try {
1909
+ const response$41 = await fetch(buildUrl(path), {
1910
+ method,
1911
+ headers: buildHeaders(),
1912
+ signal,
1913
+ credentials: getCredentials()
1914
+ });
1915
+ if (!response$41.ok) {
1916
+ let errorBody;
1917
+ try {
1918
+ errorBody = await response$41.json();
1919
+ } catch {
1920
+ errorBody = void 0;
1921
+ }
1922
+ return {
1923
+ ok: false,
1924
+ error: createHttpError(response$41.status, response$41.statusText, errorBody)
1925
+ };
1926
+ }
1927
+ return {
1928
+ ok: true,
1929
+ data: void 0
1930
+ };
1931
+ } catch (error) {
1932
+ if (error instanceof Error && error.name === "AbortError") return {
1933
+ ok: false,
1934
+ error: createAbortError()
1935
+ };
1936
+ return {
1937
+ ok: false,
1938
+ error: createNetworkError(error)
1939
+ };
1940
+ } finally {
1941
+ cleanup();
1942
+ }
1943
+ }
1944
+ return {
1945
+ get: (path, options) => request$39("GET", path, void 0, options),
1946
+ post: (path, body, options) => request$39("POST", path, body, options),
1947
+ put: (path, body, options) => request$39("PUT", path, body, options),
1948
+ delete: (path, options) => request$39("DELETE", path, void 0, options),
1949
+ deleteNoContent: (path, options) => requestNoContent("DELETE", path, options),
1950
+ getBlob: (path, options) => requestBlob(path, options),
1951
+ getStream: (path, options) => requestStream(path, options)
1952
+ };
1953
+ }
1954
+
1955
+ //#endregion
1956
+ //#region src/client.ts
1957
+ function createApiClient(config) {
1958
+ const fetcher = createFetcher(config);
1959
+ return {
1960
+ applications: createApplicationsApi(fetcher),
1961
+ env: createEnvApi(fetcher),
1962
+ jobs: createJobsApi(fetcher),
1963
+ experts: createExpertsApi(fetcher)
1964
+ };
1965
+ }
1966
+
1967
+ //#endregion
1968
+ //#region src/lib/api-key.ts
1969
+ function matchWildcard(value, pattern) {
1970
+ if (pattern === "*") return true;
1971
+ if (pattern.endsWith("*")) return value.startsWith(pattern.slice(0, -1));
1972
+ if (pattern.startsWith("*")) return value.endsWith(pattern.slice(1));
1973
+ return value === pattern;
1974
+ }
1975
+ function matchOperations(operations, requiredOperation) {
1976
+ return operations.some((pattern) => matchWildcard(requiredOperation, pattern));
1977
+ }
1978
+ function matchExperts(experts, expertId) {
1979
+ if (experts === void 0 || experts === "*") return true;
1980
+ return experts.some((pattern) => matchWildcard(expertId, pattern));
1981
+ }
1982
+ function isApiKeyPermissions(parsed) {
1983
+ return typeof parsed === "object" && parsed !== null && "operations" in parsed && Array.isArray(parsed.operations);
1984
+ }
1985
+ function parseApiKeyPermissions(permissionsJson) {
1986
+ if (!permissionsJson) return null;
1987
+ try {
1988
+ const parsed = JSON.parse(permissionsJson);
1989
+ if (!isApiKeyPermissions(parsed)) return null;
1990
+ return parsed;
1991
+ } catch {
1992
+ return null;
1993
+ }
1994
+ }
1995
+ function stringifyApiKeyPermissions(permissions) {
1996
+ return JSON.stringify(permissions);
1997
+ }
1998
+
1999
+ //#endregion
2000
+ //#region src/lib/auth.ts
2001
+ /**
2002
+ * Build authentication headers from AuthOptions.
2003
+ */
2004
+ function buildAuthHeaders(auth) {
2005
+ if (auth.type === "apiKey") return { Authorization: `Bearer ${auth.apiKey}` };
2006
+ return { Cookie: auth.cookie };
2007
+ }
2008
+
2009
+ //#endregion
2010
+ export { buildAuthHeaders, createAbortError, createApiClient, createFetcher, createHttpError, createNetworkError, createValidationError, matchExperts, matchOperations, matchWildcard, parseApiKeyPermissions, parseSSE, stringifyApiKeyPermissions };
2011
+ //# sourceMappingURL=index.mjs.map