@kraken-ai/platform 0.0.4 → 0.0.7

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,4 +1,4 @@
1
- // src/agents/errors.ts
1
+ // ../../../private-packages/platform-core/dist/errors.js
2
2
  var SecurityError = class extends Error {
3
3
  code = "SECURITY_VIOLATION";
4
4
  constructor(message) {
@@ -14,6 +14,217 @@ var ConnectorError = class extends Error {
14
14
  }
15
15
  };
16
16
 
17
+ // ../../../private-packages/platform-core/dist/qualified-name.js
18
+ var qualify = (repoName, primitiveName) => {
19
+ if (!repoName)
20
+ throw new Error("repoName must not be empty");
21
+ if (!primitiveName)
22
+ throw new Error("primitiveName must not be empty");
23
+ return `${repoName}/${primitiveName}`;
24
+ };
25
+ var parse = (qualified) => {
26
+ const slashIndex = qualified.indexOf("/");
27
+ if (slashIndex === -1) {
28
+ throw new Error(`Expected qualified name with "/" separator, got: "${qualified}"`);
29
+ }
30
+ if (qualified.indexOf("/", slashIndex + 1) !== -1) {
31
+ throw new Error(`Expected exactly one "/" in qualified name, got: "${qualified}"`);
32
+ }
33
+ const repoName = qualified.slice(0, slashIndex);
34
+ const primitiveName = qualified.slice(slashIndex + 1);
35
+ if (!repoName || !primitiveName) {
36
+ throw new Error(`Both repo and primitive segments must be non-empty, got: "${qualified}"`);
37
+ }
38
+ return { repoName, primitiveName };
39
+ };
40
+ var isQualified = (name) => {
41
+ const slashIndex = name.indexOf("/");
42
+ if (slashIndex === -1 || slashIndex === 0 || slashIndex === name.length - 1)
43
+ return false;
44
+ return name.indexOf("/", slashIndex + 1) === -1;
45
+ };
46
+
47
+ // ../../../private-packages/platform-core/dist/types/action.js
48
+ var ACTION_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;
49
+ var isValidActionName = (name) => name.length === 1 ? /^[a-z0-9]$/.test(name) : ACTION_NAME_REGEX.test(name);
50
+
51
+ // ../../../private-packages/platform-core/dist/types/environment.js
52
+ import * as z from "zod";
53
+ var environmentSchema = z.enum(["dev", "staging", "prod"]);
54
+
55
+ // ../../../private-packages/platform-core/dist/types/identity.js
56
+ import * as z2 from "zod";
57
+ var jitPolicySchema = z2.enum(["auto-approve", "policy-based", "require-approval"]);
58
+ var identityConfigSchema = z2.object({
59
+ basePermissions: z2.array(z2.string()),
60
+ requestablePermissions: z2.array(z2.string()).optional(),
61
+ jitPolicy: jitPolicySchema.optional(),
62
+ maxJitDurationMinutes: z2.number().int().positive().optional()
63
+ });
64
+
65
+ // ../../../private-packages/platform-core/dist/types/notifications.js
66
+ import * as z3 from "zod";
67
+ var notificationConfigSchema = z3.object({
68
+ slack: z3.string().optional(),
69
+ onSuccess: z3.boolean().optional(),
70
+ onFailure: z3.boolean().optional(),
71
+ onTimeout: z3.boolean().optional()
72
+ });
73
+
74
+ // ../../../private-packages/platform-core/dist/types/platform-agent.js
75
+ import * as z7 from "zod";
76
+
77
+ // ../../../private-packages/platform-core/dist/validate.js
78
+ var PRIMITIVE_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;
79
+ var isValidPrimitiveName = (name) => name.length === 1 ? /^[a-z0-9]$/.test(name) : PRIMITIVE_NAME_REGEX.test(name);
80
+ var SKILL_NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}[a-zA-Z0-9]$/;
81
+ var isValidSkillName = (basename) => basename.length === 1 ? /^[a-zA-Z0-9]$/.test(basename) : SKILL_NAME_REGEX.test(basename);
82
+ var isValidSkillId = (id) => {
83
+ const base = id.endsWith(".md") ? id.slice(0, -3) : id;
84
+ return isValidSkillName(base);
85
+ };
86
+ var isValidQualifiedName = (name) => {
87
+ if (!isQualified(name))
88
+ return false;
89
+ const { repoName, primitiveName } = parse(name);
90
+ return isValidPrimitiveName(repoName) && isValidPrimitiveName(primitiveName);
91
+ };
92
+ var isValidQualifiedSkillId = (id) => {
93
+ if (!isQualified(id))
94
+ return false;
95
+ const { repoName, primitiveName } = parse(id);
96
+ return isValidPrimitiveName(repoName) && isValidSkillId(primitiveName);
97
+ };
98
+
99
+ // ../../../private-packages/platform-core/dist/types/resources.js
100
+ import * as z4 from "zod";
101
+ var resourceLimitsSchema = z4.object({
102
+ maxTokens: z4.number().int().positive().optional(),
103
+ maxCostUsd: z4.number().positive().optional(),
104
+ timeoutSeconds: z4.number().int().positive().optional()
105
+ });
106
+ var retryPolicySchema = z4.object({
107
+ maxAttempts: z4.number().int().min(1).optional(),
108
+ backoffSeconds: z4.number().positive().optional()
109
+ });
110
+ var concurrencyPolicySchema = z4.object({
111
+ maxParallelRuns: z4.number().int().min(1).optional()
112
+ });
113
+
114
+ // ../../../private-packages/platform-core/dist/types/team.js
115
+ import * as z5 from "zod";
116
+ var teamConfigSchema = z5.object({
117
+ members: z5.array(z5.string()).min(1),
118
+ maxConcurrentWorkers: z5.number().int().min(1).optional(),
119
+ maxTokenBudgetPerWorker: z5.number().int().positive().optional(),
120
+ maxDurationPerWorker: z5.number().positive().optional()
121
+ });
122
+
123
+ // ../../../private-packages/platform-core/dist/types/trigger.js
124
+ import * as z6 from "zod";
125
+ var cronTriggerSchema = z6.object({
126
+ type: z6.literal("cron"),
127
+ expression: z6.string(),
128
+ timezone: z6.string().optional()
129
+ });
130
+ var webhookTriggerSchema = z6.object({
131
+ type: z6.literal("webhook"),
132
+ path: z6.string().startsWith("/"),
133
+ method: z6.enum(["POST", "GET"]).optional()
134
+ });
135
+ var eventTriggerSchema = z6.object({
136
+ type: z6.literal("event"),
137
+ source: z6.string(),
138
+ event: z6.string()
139
+ });
140
+ var apiTriggerSchema = z6.object({ type: z6.literal("api") });
141
+ var manualTriggerSchema = z6.object({ type: z6.literal("manual") });
142
+ var triggerConfigSchema = z6.discriminatedUnion("type", [
143
+ cronTriggerSchema,
144
+ webhookTriggerSchema,
145
+ eventTriggerSchema,
146
+ apiTriggerSchema,
147
+ manualTriggerSchema
148
+ ]);
149
+
150
+ // ../../../private-packages/platform-core/dist/types/platform-agent.js
151
+ var thinkingLevelSchema = z7.enum(["low", "medium", "high"]);
152
+ var logLevelSchema = z7.enum(["silent", "debug", "info", "warn", "error"]);
153
+ var agentDefinitionSchema = z7.object({
154
+ name: z7.string().min(1),
155
+ model: z7.string().min(1),
156
+ instructions: z7.string().min(1),
157
+ description: z7.string().optional(),
158
+ skills: z7.array(z7.string()).optional(),
159
+ temperature: z7.number().min(0).max(2).optional(),
160
+ allowTemperatureOverride: z7.boolean().optional(),
161
+ maxOutputTokens: z7.number().int().positive().optional(),
162
+ thinkingLevel: thinkingLevelSchema.optional(),
163
+ logLevel: logLevelSchema.optional()
164
+ }).strict();
165
+ var platformAgentConfigSchema = z7.object({
166
+ agent: agentDefinitionSchema,
167
+ connectors: z7.array(z7.string()).optional(),
168
+ triggers: z7.array(triggerConfigSchema),
169
+ identity: identityConfigSchema.optional(),
170
+ resources: resourceLimitsSchema.optional(),
171
+ retries: retryPolicySchema.optional(),
172
+ concurrency: concurrencyPolicySchema.optional(),
173
+ fast: z7.boolean().optional(),
174
+ team: teamConfigSchema.optional(),
175
+ notifications: notificationConfigSchema.optional(),
176
+ environment: environmentSchema.optional(),
177
+ actions: z7.array(z7.string()).optional()
178
+ }).strict().superRefine((data, ctx) => {
179
+ for (const member of data.team?.members ?? []) {
180
+ const valid = isQualified(member) ? isValidQualifiedName(member) : isValidPrimitiveName(member);
181
+ if (!valid) {
182
+ ctx.addIssue({
183
+ code: z7.ZodIssueCode.custom,
184
+ path: ["team", "members"],
185
+ message: `Invalid team member name: "${member}"`
186
+ });
187
+ }
188
+ }
189
+ for (const connector of data.connectors ?? []) {
190
+ const valid = isQualified(connector) ? isValidQualifiedName(connector) : isValidPrimitiveName(connector);
191
+ if (!valid) {
192
+ ctx.addIssue({
193
+ code: z7.ZodIssueCode.custom,
194
+ path: ["connectors"],
195
+ message: `Invalid connector name: "${connector}"`
196
+ });
197
+ }
198
+ }
199
+ for (const skill of data.agent.skills ?? []) {
200
+ const valid = isQualified(skill) ? isValidQualifiedSkillId(skill) : isValidSkillId(skill);
201
+ if (!valid) {
202
+ ctx.addIssue({
203
+ code: z7.ZodIssueCode.custom,
204
+ path: ["agent", "skills"],
205
+ message: `Invalid skill ID: "${skill}"`
206
+ });
207
+ }
208
+ }
209
+ for (const action of data.actions ?? []) {
210
+ const valid = isQualified(action) ? isValidQualifiedName(action) : isValidPrimitiveName(action);
211
+ if (!valid) {
212
+ ctx.addIssue({
213
+ code: z7.ZodIssueCode.custom,
214
+ path: ["actions"],
215
+ message: `Invalid action name: "${action}"`
216
+ });
217
+ }
218
+ }
219
+ });
220
+
221
+ // ../../../private-packages/platform-core/dist/types/skill.js
222
+ import * as z8 from "zod";
223
+ var platformSkillInputSchema = z8.object({
224
+ name: z8.string().min(1),
225
+ description: z8.string().optional()
226
+ }).strict();
227
+
17
228
  // src/agents/connector-wrap.ts
18
229
  var MAX_TOOL_RESULT_SIZE = 10 * 1024 * 1024;
19
230
  var isMcpContent = (val) => typeof val === "object" && val !== null && "__mcpPassThrough" in val && val.__mcpPassThrough === true;
@@ -69,7 +280,7 @@ var mcpResult = (content, isError) => ({
69
280
  // src/agents/connector-server.ts
70
281
  import { randomUUID } from "crypto";
71
282
  import { createServer } from "http";
72
- import * as z from "zod";
283
+ import * as z9 from "zod";
73
284
  var DEFAULT_HANDLER_TIMEOUT_MS = 3e4;
74
285
  var MAX_BODY_SIZE = 10 * 1024 * 1024;
75
286
  var withTimeout = (promise, ms) => Promise.race([
@@ -97,7 +308,7 @@ var buildPromptArgsSchema = (def) => {
97
308
  if (!def.arguments?.length) return void 0;
98
309
  const shape = {};
99
310
  for (const arg of def.arguments) {
100
- shape[arg.name] = arg.required ? z.string() : z.string().optional();
311
+ shape[arg.name] = arg.required ? z9.string() : z9.string().optional();
101
312
  }
102
313
  return shape;
103
314
  };
@@ -283,70 +494,38 @@ var startConnectorServer = async (connector, options) => {
283
494
  };
284
495
  };
285
496
 
286
- // src/agents/types/action.ts
287
- import * as z2 from "zod";
288
- var ACTION_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;
289
- var isValidActionName = (name) => name.length === 1 ? /^[a-z0-9]$/.test(name) : ACTION_NAME_REGEX.test(name);
290
- var actionVariantConfigSchema = z2.object({
291
- schema: z2.record(z2.string(), z2.unknown()),
292
- webhook: z2.string().url().optional(),
293
- hasHandler: z2.boolean()
294
- });
295
- var actionsConfigSchema = z2.object({
296
- variants: z2.record(z2.string(), actionVariantConfigSchema)
297
- }).strict();
298
-
299
497
  // src/agents/define-actions.ts
300
- import * as z3 from "zod";
301
- var defineAction = (input) => input;
302
- var defineActions = (variants) => {
303
- const entries = Object.entries(variants);
304
- if (entries.length === 0) {
305
- throw new Error("defineActions() requires at least one action variant");
306
- }
307
- if (entries.length > 20) {
308
- throw new Error("defineActions() supports a maximum of 20 action variants");
309
- }
310
- const serialized = {};
311
- const zodSchemas = {};
312
- const handlers = {};
313
- for (const [name, variant] of entries) {
314
- if (!isValidActionName(name)) {
315
- throw new Error(
316
- `Invalid action name "${name}": must be lowercase alphanumeric with hyphens, 1-64 chars`
317
- );
318
- }
319
- const v = variant;
320
- serialized[name] = {
321
- schema: z3.toJSONSchema(v.schema, { target: "draft-2020-12" }),
322
- webhook: v.webhook,
323
- hasHandler: !!v.handler
324
- };
325
- zodSchemas[name] = v.schema;
326
- if (v.handler) {
327
- handlers[name] = v.handler;
328
- }
498
+ import * as z10 from "zod";
499
+ var defineAction = (input) => {
500
+ if (!input.name || !isValidActionName(input.name)) {
501
+ throw new Error(
502
+ `Invalid action name "${input.name}": must be lowercase alphanumeric with hyphens, 1-64 chars`
503
+ );
329
504
  }
330
505
  return Object.freeze({
331
- __type: "PlatformActions",
332
- config: Object.freeze({ variants: Object.freeze(serialized) }),
333
- zodSchemas: Object.freeze(zodSchemas),
334
- handlers: Object.freeze(handlers)
506
+ __type: "PlatformAction",
507
+ name: input.name,
508
+ config: Object.freeze({
509
+ schema: z10.toJSONSchema(input.schema, { target: "draft-2020-12" }),
510
+ webhook: input.webhook,
511
+ hasHandler: !!input.handler
512
+ }),
513
+ zodSchema: input.schema,
514
+ handler: input.handler
335
515
  });
336
516
  };
337
517
  var buildActionOutputSchema = (actions) => {
338
- const entries = Object.entries(actions.zodSchemas);
339
- if (entries.length === 0) {
518
+ if (actions.length === 0) {
340
519
  throw new Error("Cannot build output schema from empty action definitions");
341
520
  }
342
- const variants = entries.map(
343
- ([name, schema]) => z3.object({ action: z3.literal(name) }).extend(schema.shape)
521
+ const variants = actions.map(
522
+ (action) => z10.object({ action: z10.literal(action.name) }).extend(action.zodSchema.shape)
344
523
  );
345
524
  const [first, ...rest] = variants;
346
525
  if (!first) {
347
526
  throw new Error("Cannot build output schema from empty action definitions");
348
527
  }
349
- return z3.discriminatedUnion("action", [first, ...rest]);
528
+ return z10.discriminatedUnion("action", [first, ...rest]);
350
529
  };
351
530
 
352
531
  // src/cli/log.ts
@@ -363,29 +542,27 @@ var yellow = code(33, 39);
363
542
  var green = code(32, 39);
364
543
  var cyan = code(36, 39);
365
544
 
366
- // src/cli/validate.ts
367
- var ENTITY_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;
368
- var isValidEntityName = (name) => name.length === 1 ? /^[a-z0-9]$/.test(name) : ENTITY_NAME_REGEX.test(name);
369
-
370
545
  export {
371
546
  SecurityError,
372
547
  ConnectorError,
548
+ qualify,
549
+ parse,
550
+ isQualified,
551
+ ACTION_NAME_REGEX,
552
+ isValidActionName,
553
+ PRIMITIVE_NAME_REGEX,
554
+ isValidPrimitiveName,
555
+ platformAgentConfigSchema,
556
+ platformSkillInputSchema,
373
557
  wrapToolResult,
374
558
  wrapToolError,
375
559
  mcpResult,
376
560
  startConnectorServer,
377
- ACTION_NAME_REGEX,
378
- isValidActionName,
379
- actionVariantConfigSchema,
380
- actionsConfigSchema,
381
561
  defineAction,
382
- defineActions,
383
562
  buildActionOutputSchema,
384
563
  dim,
385
564
  yellow,
386
565
  green,
387
- cyan,
388
- ENTITY_NAME_REGEX,
389
- isValidEntityName
566
+ cyan
390
567
  };
391
- //# sourceMappingURL=chunk-PPT6GGYL.js.map
568
+ //# sourceMappingURL=chunk-FTLOWV2N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../private-packages/platform-core/src/errors.ts","../../../../private-packages/platform-core/src/qualified-name.ts","../../../../private-packages/platform-core/src/types/action.ts","../../../../private-packages/platform-core/src/types/environment.ts","../../../../private-packages/platform-core/src/types/identity.ts","../../../../private-packages/platform-core/src/types/notifications.ts","../../../../private-packages/platform-core/src/types/platform-agent.ts","../../../../private-packages/platform-core/src/validate.ts","../../../../private-packages/platform-core/src/types/resources.ts","../../../../private-packages/platform-core/src/types/team.ts","../../../../private-packages/platform-core/src/types/trigger.ts","../../../../private-packages/platform-core/src/types/skill.ts","../src/agents/connector-wrap.ts","../src/agents/connector-server.ts","../src/agents/define-actions.ts","../src/cli/log.ts"],"sourcesContent":["export class SecurityError extends Error {\n readonly code = \"SECURITY_VIOLATION\";\n\n constructor(message: string) {\n super(message);\n this.name = \"SecurityError\";\n }\n}\n\nexport class ConnectorError extends Error {\n readonly code = \"CONNECTOR_ERROR\";\n\n constructor(message: string) {\n super(message);\n this.name = \"ConnectorError\";\n }\n}\n","/**\n * Joins a repo name and primitive name into the qualified `repo/primitive` form.\n * Throws if either segment is empty.\n */\nexport const qualify = (repoName: string, primitiveName: string): string => {\n if (!repoName) throw new Error(\"repoName must not be empty\");\n if (!primitiveName) throw new Error(\"primitiveName must not be empty\");\n return `${repoName}/${primitiveName}`;\n};\n\n/**\n * Splits a qualified name into its repo and primitive components.\n * Requires exactly one `/` with non-empty segments on both sides.\n */\nexport const parse = (qualified: string): { repoName: string; primitiveName: string } => {\n const slashIndex = qualified.indexOf(\"/\");\n if (slashIndex === -1) {\n throw new Error(`Expected qualified name with \"/\" separator, got: \"${qualified}\"`);\n }\n if (qualified.indexOf(\"/\", slashIndex + 1) !== -1) {\n throw new Error(`Expected exactly one \"/\" in qualified name, got: \"${qualified}\"`);\n }\n const repoName = qualified.slice(0, slashIndex);\n const primitiveName = qualified.slice(slashIndex + 1);\n if (!repoName || !primitiveName) {\n throw new Error(`Both repo and primitive segments must be non-empty, got: \"${qualified}\"`);\n }\n return { repoName, primitiveName };\n};\n\n/**\n * Returns true if the name is in qualified `repo/entity` form —\n * exactly one `/` with non-empty segments on both sides.\n * Purely structural; no format validation.\n */\nexport const isQualified = (name: string): boolean => {\n const slashIndex = name.indexOf(\"/\");\n if (slashIndex === -1 || slashIndex === 0 || slashIndex === name.length - 1) return false;\n return name.indexOf(\"/\", slashIndex + 1) === -1;\n};\n","import type * as z from \"zod\";\n\n/** Action names follow entity naming convention: lowercase alphanumeric with hyphens, 1-64 chars. */\nexport const ACTION_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;\n\n/** Validates an action name (allows single-char names like \"a\"). */\nexport const isValidActionName = (name: string): boolean =>\n name.length === 1 ? /^[a-z0-9]$/.test(name) : ACTION_NAME_REGEX.test(name);\n\n/** Input for a single action in defineAction(). */\nexport interface ActionVariantInput<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> {\n name: string;\n schema: S;\n webhook?: string;\n // Method syntax → bivariant parameter checking, so specific handler args\n // (e.g. { reason: string }) are assignable to the default (z.infer<ZodObject>).\n handler?(payload: z.infer<S>): Promise<void>;\n}\n\n/** Serializable config for a single action (stored in manifest/DB). */\nexport interface ActionConfig {\n schema: Record<string, unknown>;\n webhook?: string;\n hasHandler: boolean;\n}\n\n/** Branded action type returned by defineAction(). */\nexport interface PlatformAction {\n readonly __type: \"PlatformAction\";\n readonly name: string;\n readonly config: ActionConfig;\n readonly zodSchema: z.ZodObject<z.ZodRawShape>;\n readonly handler?: (payload: unknown) => Promise<void>;\n}\n","import * as z from \"zod\";\n\nexport const environmentSchema = z.enum([\"dev\", \"staging\", \"prod\"]);\n\nexport type Environment = z.infer<typeof environmentSchema>;\n","import * as z from \"zod\";\n\nexport const jitPolicySchema = z.enum([\"auto-approve\", \"policy-based\", \"require-approval\"]);\n\nexport type JitPolicy = z.infer<typeof jitPolicySchema>;\n\nexport const identityConfigSchema = z.object({\n basePermissions: z.array(z.string()),\n requestablePermissions: z.array(z.string()).optional(),\n jitPolicy: jitPolicySchema.optional(),\n maxJitDurationMinutes: z.number().int().positive().optional(),\n});\n\nexport type IdentityConfig = z.infer<typeof identityConfigSchema>;\n","import * as z from \"zod\";\n\nexport const notificationConfigSchema = z.object({\n slack: z.string().optional(),\n onSuccess: z.boolean().optional(),\n onFailure: z.boolean().optional(),\n onTimeout: z.boolean().optional(),\n});\n\nexport type NotificationConfig = z.infer<typeof notificationConfigSchema>;\n","import type { ModelString } from \"kraken-ai\";\nimport * as z from \"zod\";\nimport { isQualified } from \"../qualified-name\";\nimport {\n isValidPrimitiveName,\n isValidQualifiedName,\n isValidQualifiedSkillId,\n isValidSkillId,\n} from \"../validate\";\nimport { environmentSchema } from \"./environment\";\nimport { identityConfigSchema } from \"./identity\";\nimport { notificationConfigSchema } from \"./notifications\";\nimport { concurrencyPolicySchema, resourceLimitsSchema, retryPolicySchema } from \"./resources\";\nimport { teamConfigSchema } from \"./team\";\nimport { triggerConfigSchema } from \"./trigger\";\n\nconst thinkingLevelSchema = z.enum([\"low\", \"medium\", \"high\"]);\n\nconst logLevelSchema = z.enum([\"silent\", \"debug\", \"info\", \"warn\", \"error\"]);\n\nexport const agentDefinitionSchema = z\n .object({\n name: z.string().min(1),\n model: z.string().min(1),\n instructions: z.string().min(1),\n description: z.string().optional(),\n skills: z.array(z.string()).optional(),\n temperature: z.number().min(0).max(2).optional(),\n allowTemperatureOverride: z.boolean().optional(),\n maxOutputTokens: z.number().int().positive().optional(),\n thinkingLevel: thinkingLevelSchema.optional(),\n logLevel: logLevelSchema.optional(),\n })\n .strict();\n\nexport type AgentDefinition = Omit<z.infer<typeof agentDefinitionSchema>, \"model\"> & {\n model: ModelString;\n};\n\nexport const platformAgentConfigSchema = z\n .object({\n agent: agentDefinitionSchema,\n connectors: z.array(z.string()).optional(),\n triggers: z.array(triggerConfigSchema),\n identity: identityConfigSchema.optional(),\n resources: resourceLimitsSchema.optional(),\n retries: retryPolicySchema.optional(),\n concurrency: concurrencyPolicySchema.optional(),\n fast: z.boolean().optional(),\n team: teamConfigSchema.optional(),\n notifications: notificationConfigSchema.optional(),\n environment: environmentSchema.optional(),\n actions: z.array(z.string()).optional(),\n })\n .strict()\n .superRefine((data, ctx) => {\n // Validate team member references\n for (const member of data.team?.members ?? []) {\n const valid = isQualified(member)\n ? isValidQualifiedName(member)\n : isValidPrimitiveName(member);\n if (!valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"team\", \"members\"],\n message: `Invalid team member name: \"${member}\"`,\n });\n }\n }\n\n // Validate connector references\n for (const connector of data.connectors ?? []) {\n const valid = isQualified(connector)\n ? isValidQualifiedName(connector)\n : isValidPrimitiveName(connector);\n if (!valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"connectors\"],\n message: `Invalid connector name: \"${connector}\"`,\n });\n }\n }\n\n // Validate skill references\n for (const skill of data.agent.skills ?? []) {\n const valid = isQualified(skill) ? isValidQualifiedSkillId(skill) : isValidSkillId(skill);\n if (!valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"agent\", \"skills\"],\n message: `Invalid skill ID: \"${skill}\"`,\n });\n }\n }\n\n // Validate action references\n for (const action of data.actions ?? []) {\n const valid = isQualified(action)\n ? isValidQualifiedName(action)\n : isValidPrimitiveName(action);\n if (!valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"actions\"],\n message: `Invalid action name: \"${action}\"`,\n });\n }\n }\n });\n\nexport type PlatformAgentConfig = Omit<z.infer<typeof platformAgentConfigSchema>, \"agent\"> & {\n agent: AgentDefinition;\n};\n\nexport interface PlatformAgent {\n readonly __type: \"PlatformAgent\";\n readonly config: PlatformAgentConfig;\n readonly runtime?: unknown;\n /** In-memory schemas for action variants. Not serialized — runtime use only. */\n readonly actionZodSchemas?: Record<string, import(\"zod\").ZodObject<import(\"zod\").ZodRawShape>>;\n /** Action handler functions. Not serialized — runtime use only. */\n readonly actionHandlers?: Readonly<Record<string, (payload: unknown) => Promise<void>>>;\n /** Action webhook URLs. Not serialized — runtime use only. */\n readonly actionWebhooks?: Readonly<Record<string, string | undefined>>;\n /** Team member PlatformAgent objects. Not serialized — runtime use only (dev mode delegation). */\n readonly teamAgents?: readonly PlatformAgent[];\n}\n\n/** Team member reference: local PlatformAgent or remote agent ID string. */\nexport type TeamMember = PlatformAgent | string;\n","import { isQualified, parse } from \"./qualified-name\";\n\n// ─── Primitive Name Validation ───\n\nexport const PRIMITIVE_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;\n\n/** Single-char names (e.g. \"a\") are valid — the regex requires min 2 chars, so we also allow /^[a-z0-9]$/ */\nexport const isValidPrimitiveName = (name: string): boolean =>\n name.length === 1 ? /^[a-z0-9]$/.test(name) : PRIMITIVE_NAME_REGEX.test(name);\n\n// ─── Skill Name Validation ───\n\n/** Skill filenames allow uppercase: e.g. someFile-name.md, Research.md */\nexport const SKILL_NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}[a-zA-Z0-9]$/;\n\nexport const isValidSkillName = (basename: string): boolean =>\n basename.length === 1 ? /^[a-zA-Z0-9]$/.test(basename) : SKILL_NAME_REGEX.test(basename);\n\n/** Skill IDs from remote may include .md extension */\nexport const isValidSkillId = (id: string): boolean => {\n const base = id.endsWith(\".md\") ? id.slice(0, -3) : id;\n return isValidSkillName(base);\n};\n\n// ─── Qualified Name Validation ───\n\n/** Validates a qualified `repo/primitive` name — both segments must pass `isValidPrimitiveName`. */\nexport const isValidQualifiedName = (name: string): boolean => {\n if (!isQualified(name)) return false;\n const { repoName, primitiveName } = parse(name);\n return isValidPrimitiveName(repoName) && isValidPrimitiveName(primitiveName);\n};\n\n/** Validates a qualified skill ID — repo segment passes `isValidPrimitiveName`, primitive segment passes `isValidSkillId`. */\nexport const isValidQualifiedSkillId = (id: string): boolean => {\n if (!isQualified(id)) return false;\n const { repoName, primitiveName } = parse(id);\n return isValidPrimitiveName(repoName) && isValidSkillId(primitiveName);\n};\n\n// ─── Tool Name Validation ───\n\n/** Tool names allow underscores (e.g., fs_read, fs_write) */\nexport const TOOL_NAME_REGEX = /^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;\n\nexport const isValidToolName = (name: string): boolean =>\n name.length === 1 ? /^[a-z]$/.test(name) : TOOL_NAME_REGEX.test(name);\n\n// ─── Property Name Validation ───\n\n/** JS/TS property names with 255-char length cap to prevent DoS */\nexport const PROPERTY_NAME_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]{0,254}$/;\n\nconst FORBIDDEN_PROPS = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"__defineGetter__\",\n \"__defineSetter__\",\n \"__lookupGetter__\",\n \"__lookupSetter__\",\n]);\n\nexport const isValidPropertyName = (name: string): boolean =>\n PROPERTY_NAME_REGEX.test(name) && !FORBIDDEN_PROPS.has(name);\n","import * as z from \"zod\";\n\nexport const resourceLimitsSchema = z.object({\n maxTokens: z.number().int().positive().optional(),\n maxCostUsd: z.number().positive().optional(),\n timeoutSeconds: z.number().int().positive().optional(),\n});\n\nexport type ResourceLimits = z.infer<typeof resourceLimitsSchema>;\n\nexport const retryPolicySchema = z.object({\n maxAttempts: z.number().int().min(1).optional(),\n backoffSeconds: z.number().positive().optional(),\n});\n\nexport type RetryPolicy = z.infer<typeof retryPolicySchema>;\n\nexport const concurrencyPolicySchema = z.object({\n maxParallelRuns: z.number().int().min(1).optional(),\n});\n\nexport type ConcurrencyPolicy = z.infer<typeof concurrencyPolicySchema>;\n","import * as z from \"zod\";\n\nexport const teamConfigSchema = z.object({\n members: z.array(z.string()).min(1),\n maxConcurrentWorkers: z.number().int().min(1).optional(),\n maxTokenBudgetPerWorker: z.number().int().positive().optional(),\n maxDurationPerWorker: z.number().positive().optional(),\n});\n\nexport type TeamConfig = z.infer<typeof teamConfigSchema>;\n","import * as z from \"zod\";\n\nconst cronTriggerSchema = z.object({\n type: z.literal(\"cron\"),\n expression: z.string(),\n timezone: z.string().optional(),\n});\n\nconst webhookTriggerSchema = z.object({\n type: z.literal(\"webhook\"),\n path: z.string().startsWith(\"/\"),\n method: z.enum([\"POST\", \"GET\"]).optional(),\n});\n\nconst eventTriggerSchema = z.object({\n type: z.literal(\"event\"),\n source: z.string(),\n event: z.string(),\n});\n\nconst apiTriggerSchema = z.object({ type: z.literal(\"api\") });\n\nconst manualTriggerSchema = z.object({ type: z.literal(\"manual\") });\n\nexport const triggerConfigSchema = z.discriminatedUnion(\"type\", [\n cronTriggerSchema,\n webhookTriggerSchema,\n eventTriggerSchema,\n apiTriggerSchema,\n manualTriggerSchema,\n]);\n\nexport type TriggerConfig = z.infer<typeof triggerConfigSchema>;\n","import * as z from \"zod\";\n\nexport const platformSkillInputSchema = z\n .object({\n name: z.string().min(1),\n description: z.string().optional(),\n })\n .strict();\n\nexport interface PlatformSkill {\n readonly __type: \"PlatformSkill\";\n readonly name: string;\n readonly description?: string;\n}\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport { ConnectorError, type McpContent } from \"@kraken-ai/platform-core\";\n\nconst MAX_TOOL_RESULT_SIZE = 10 * 1024 * 1024; // 10MB\n\ninterface ToolResultContent {\n readonly type: string;\n [key: string]: unknown;\n}\n\ninterface ToolResult {\n readonly content: ReadonlyArray<ToolResultContent>;\n readonly isError?: boolean;\n}\n\nconst isMcpContent = (val: unknown): val is McpContent =>\n typeof val === \"object\" &&\n val !== null &&\n \"__mcpPassThrough\" in val &&\n (val as McpContent).__mcpPassThrough === true;\n\n/**\n * Wrap a tool handler's return value into MCP `CallToolResult` format.\n *\n * Automatically converts primitives to `{ type: \"text\" }` content and\n * serializes objects to JSON. Pass-through {@link McpContent} values\n * (created with {@link mcpResult}) are forwarded as-is.\n *\n * @param value - The handler's return value (string, number, boolean,\n * object, {@link McpContent}, or `null`/`undefined`).\n * @returns An MCP-compatible tool result.\n *\n * @example\n * ```ts\n * wrapToolResult(\"done\"); // { content: [{ type: \"text\", text: \"done\" }] }\n * wrapToolResult({ id: 1 }); // { content: [{ type: \"text\", text: '{\\n \"id\": 1\\n}' }] }\n * wrapToolResult(null); // { content: [] }\n * ```\n */\nexport const wrapToolResult = (value: unknown): ToolResult => {\n if (value === null || value === undefined) {\n return { content: [] };\n }\n\n if (typeof value === \"string\") {\n return { content: [{ type: \"text\", text: value }] };\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return { content: [{ type: \"text\", text: String(value) }] };\n }\n\n if (isMcpContent(value)) {\n const result: ToolResult = { content: value.content };\n if (value.isError) {\n return { ...result, isError: true };\n }\n return result;\n }\n\n const json = JSON.stringify(value, null, 2);\n if (json.length > MAX_TOOL_RESULT_SIZE) {\n return {\n content: [{ type: \"text\", text: `[Result truncated: ${json.length} bytes]` }],\n isError: true,\n };\n }\n return { content: [{ type: \"text\", text: json }] };\n};\n\n/**\n * Wrap a thrown error into MCP `CallToolResult` format with `isError: true`.\n *\n * {@link ConnectorError} messages are forwarded to the agent as-is (they\n * are user-facing). All other errors are replaced with a generic\n * \"Internal handler error\" message and logged to stderr.\n *\n * @param error - The caught error.\n * @returns An MCP-compatible error result.\n *\n * @example\n * ```ts\n * try {\n * return wrapToolResult(await handler(args));\n * } catch (err) {\n * return wrapToolError(err);\n * }\n * ```\n */\nexport const wrapToolError = (error: unknown): ToolResult => {\n if (error instanceof ConnectorError) {\n return {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n };\n }\n\n if (error instanceof Error) {\n console.error(\"[connector] Internal handler error:\", error.message, error.stack);\n } else {\n console.error(\"[connector] Internal handler error:\", String(error));\n }\n\n return {\n content: [{ type: \"text\", text: \"Internal handler error\" }],\n isError: true,\n };\n};\n\n/**\n * Create an explicit MCP content pass-through result.\n *\n * Use this when you need full control over the MCP response — for\n * example, returning an image alongside text or marking a multi-part\n * response as an error.\n *\n * @param content - Array of MCP content blocks (`{ type: \"text\", text }`,\n * `{ type: \"image\", data, mimeType }`, etc.).\n * @param isError - If `true`, the result is marked as an error.\n * @returns An {@link McpContent} object that {@link wrapToolResult}\n * forwards without modification.\n *\n * @example\n * ```ts\n * import { mcpResult } from \"@kraken-ai/platform\";\n *\n * const screenshot = defineTool({\n * description: \"Take a screenshot\",\n * input: z.object({ url: z.string().url() }),\n * handler: async ({ url }) =>\n * mcpResult([\n * { type: \"text\", text: `Screenshot of ${url}` },\n * { type: \"image\", data: base64png, mimeType: \"image/png\" },\n * ]),\n * });\n * ```\n */\nexport const mcpResult = (content: McpContent[\"content\"], isError?: boolean): McpContent => ({\n __mcpPassThrough: true as const,\n content,\n isError,\n});\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport { randomUUID } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport type { ConnectorPromptDef, PlatformConnector } from \"@kraken-ai/platform-core\";\nimport * as z from \"zod\";\nimport { wrapToolError, wrapToolResult } from \"./connector-wrap\";\n\nconst DEFAULT_HANDLER_TIMEOUT_MS = 30_000;\nconst MAX_BODY_SIZE = 10 * 1024 * 1024; // 10MB\n\nexport interface ConnectorServerOptions {\n readonly port?: number;\n readonly host?: string;\n readonly handlerTimeoutMs?: number;\n}\n\nexport interface ConnectorServerHandle {\n readonly port: number;\n readonly close: () => Promise<void>;\n}\n\nconst withTimeout = <T>(promise: Promise<T>, ms: number): Promise<T> =>\n Promise.race([\n promise,\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(`Handler timed out after ${ms}ms`)), ms),\n ),\n ]);\n\nconst readBody = (req: IncomingMessage, maxSize: number): Promise<string> =>\n new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n req.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > maxSize) {\n req.destroy();\n reject(new Error(\"Request body too large\"));\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n\n/** Convert ConnectorPromptDef.arguments array to a raw shape for MCP SDK */\nconst buildPromptArgsSchema = (\n def: ConnectorPromptDef,\n): Record<string, z.ZodString | z.ZodOptional<z.ZodString>> | undefined => {\n if (!def.arguments?.length) return undefined;\n const shape: Record<string, z.ZodString | z.ZodOptional<z.ZodString>> = {};\n for (const arg of def.arguments) {\n shape[arg.name] = arg.required ? z.string() : z.string().optional();\n }\n return shape;\n};\n\nexport const startConnectorServer = async (\n connector: PlatformConnector,\n options?: ConnectorServerOptions,\n): Promise<ConnectorServerHandle> => {\n const mcpServerModule = await import(\"@modelcontextprotocol/sdk/server/mcp.js\").catch(() => {\n throw new Error(\n \"@modelcontextprotocol/sdk is required for startConnectorServer. \" +\n \"Install it: pnpm add @modelcontextprotocol/sdk\",\n );\n });\n const transportModule = await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\").catch(\n () => {\n throw new Error(\n \"@modelcontextprotocol/sdk is required for startConnectorServer. \" +\n \"Install it: pnpm add @modelcontextprotocol/sdk\",\n );\n },\n );\n\n const { McpServer } = mcpServerModule;\n const { StreamableHTTPServerTransport } = transportModule;\n\n const timeoutMs = options?.handlerTimeoutMs ?? DEFAULT_HANDLER_TIMEOUT_MS;\n\n const mcpServer = new McpServer(\n { name: connector.name, version: \"0.0.0\" },\n { capabilities: { tools: {}, resources: {}, prompts: {} } },\n );\n\n const tools = connector.tools ?? {};\n const toolEntries = Object.entries(tools);\n\n if (toolEntries.length === 0) {\n console.warn(\n `[connector:${connector.name}] No tools defined — server will start with zero tools`,\n );\n }\n\n for (const [name, def] of toolEntries) {\n mcpServer.registerTool(\n name,\n {\n description: def.description,\n inputSchema: def.input,\n ...(def.annotations ? { annotations: def.annotations } : {}),\n },\n async (args: unknown) => {\n try {\n // args is already validated by the MCP SDK against the Zod schema\n const result = await withTimeout(Promise.resolve(def.handler(args)), timeoutMs);\n const wrapped = wrapToolResult(result);\n return {\n content: wrapped.content.map((c) => ({\n type: \"text\" as const,\n text: String(\"text\" in c ? c.text : \"\"),\n })),\n ...(wrapped.isError === true ? { isError: true as const } : {}),\n };\n } catch (error: unknown) {\n const wrapped = wrapToolError(error);\n return {\n content: wrapped.content.map((c) => ({\n type: \"text\" as const,\n text: String(\"text\" in c ? c.text : \"\"),\n })),\n isError: true as const,\n };\n }\n },\n );\n }\n\n const resources = connector.resources ?? {};\n for (const [name, def] of Object.entries(resources)) {\n mcpServer.registerResource(\n name,\n def.uri,\n {\n description: def.description,\n ...(def.mimeType ? { mimeType: def.mimeType } : {}),\n },\n async (_uri: URL, extra: { signal: AbortSignal }) => {\n try {\n const result = await withTimeout(\n Promise.resolve(def.read({ signal: extra.signal })),\n timeoutMs,\n );\n return { contents: [...result.contents] };\n } catch (error: unknown) {\n if (error instanceof Error) {\n console.error(`[connector:${connector.name}] Resource read error:`, error.message);\n }\n throw error;\n }\n },\n );\n }\n\n const prompts = connector.prompts ?? {};\n for (const [name, def] of Object.entries(prompts)) {\n const argsSchema = buildPromptArgsSchema(def);\n mcpServer.registerPrompt(\n name,\n {\n description: def.description,\n ...(argsSchema ? { argsSchema } : {}),\n },\n async (args: Record<string, string | undefined>, extra: { signal: AbortSignal }) => {\n try {\n const cleanArgs: Record<string, string> = {};\n for (const [k, v] of Object.entries(args)) {\n if (v !== undefined) cleanArgs[k] = v;\n }\n const result = await withTimeout(\n Promise.resolve(def.get(cleanArgs, { signal: extra.signal })),\n timeoutMs,\n );\n return { messages: [...result.messages] };\n } catch (error: unknown) {\n if (error instanceof Error) {\n console.error(`[connector:${connector.name}] Prompt get error:`, error.message);\n }\n throw error;\n }\n },\n );\n }\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n });\n\n const host = options?.host ?? \"127.0.0.1\";\n const port = options?.port ?? 0;\n\n const httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {\n if (req.url === \"/health\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ status: \"ok\" }));\n return;\n }\n\n if (\n req.url === \"/mcp\" &&\n (req.method === \"POST\" || req.method === \"GET\" || req.method === \"DELETE\")\n ) {\n if (req.method === \"POST\") {\n // Check Content-Length before reading body (fast reject for oversized payloads)\n const contentLength = parseInt(req.headers[\"content-length\"] ?? \"0\", 10);\n if (contentLength > MAX_BODY_SIZE) {\n req.resume(); // drain the request body to prevent EPIPE\n res.writeHead(413, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Request body too large\" }));\n return;\n }\n\n try {\n const body = await readBody(req, MAX_BODY_SIZE);\n const parsed: unknown = JSON.parse(body);\n await transport.handleRequest(req, res, parsed);\n } catch (err: unknown) {\n if (!res.headersSent) {\n const isTooLarge = err instanceof Error && err.message === \"Request body too large\";\n res.writeHead(isTooLarge ? 413 : 400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: isTooLarge ? \"Request body too large\" : \"Invalid request body\",\n }),\n );\n }\n }\n return;\n }\n\n // GET (SSE) and DELETE (session end)\n try {\n await transport.handleRequest(req, res);\n } catch {\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n }\n }\n return;\n }\n\n res.writeHead(404);\n res.end(\"Not found\");\n });\n\n // Connect MCP server to transport AFTER tool registration\n await mcpServer.connect(transport);\n\n await new Promise<void>((resolve) => {\n httpServer.listen(port, host, () => resolve());\n });\n\n const addr = httpServer.address();\n if (!addr || typeof addr === \"string\") {\n throw new Error(\"Failed to get server address\");\n }\n\n return {\n port: (addr as AddressInfo).port,\n close: async () => {\n await mcpServer.close();\n await new Promise<void>((resolve, reject) => {\n httpServer.close((err: Error | undefined) => (err ? reject(err) : resolve()));\n });\n },\n };\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport {\n type ActionVariantInput,\n isValidActionName,\n type PlatformAction,\n} from \"@kraken-ai/platform-core\";\nimport * as z from \"zod\";\n\n/**\n * Define a standalone action with a name, Zod schema, optional webhook, and\n * optional handler.\n *\n * Actions are the agent's typed terminal outputs — each action is a possible\n * decision the agent can make. The handler's payload type is inferred from\n * the schema, giving you end-to-end type safety.\n *\n * @param input - Action name, schema, optional webhook URL, and optional handler.\n * @returns A frozen {@link PlatformAction} object.\n * @throws If `name` is empty, invalid, or longer than 64 chars.\n *\n * @example\n * ```ts\n * import { defineAction } from \"@kraken-ai/platform\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * name: \"approve\",\n * schema: z.object({ reason: z.string(), confidence: z.number() }),\n * handler: async (payload) => {\n * payload.reason; // string\n * payload.confidence; // number\n * },\n * });\n * ```\n */\nexport const defineAction = <S extends z.ZodObject<z.ZodRawShape>>(\n input: ActionVariantInput<S>,\n): PlatformAction => {\n if (!input.name || !isValidActionName(input.name)) {\n throw new Error(\n `Invalid action name \"${input.name}\": must be lowercase alphanumeric with hyphens, 1-64 chars`,\n );\n }\n\n return Object.freeze({\n __type: \"PlatformAction\" as const,\n name: input.name,\n config: Object.freeze({\n schema: z.toJSONSchema(input.schema, { target: \"draft-2020-12\" }) as Record<string, unknown>,\n webhook: input.webhook,\n hasHandler: !!input.handler,\n }),\n zodSchema: input.schema,\n handler: input.handler as ((payload: unknown) => Promise<void>) | undefined,\n });\n};\n\n/**\n * Build a discriminated-union Zod schema from action definitions.\n *\n * Each action becomes `z.object({ action: z.literal(name), ...fields })`,\n * and the union discriminates on the `action` key. Pass the result as\n * `outputSchema` in {@link definePlatformAgent} to constrain the agent's\n * structured output to exactly one of the defined actions.\n *\n * @param actions - Array of {@link PlatformAction} objects returned by {@link defineAction}.\n * @returns A `z.ZodDiscriminatedUnion` schema.\n * @throws If `actions` is empty.\n *\n * @example\n * ```ts\n * import { defineAction, buildActionOutputSchema } from \"@kraken-ai/platform\";\n * import { z } from \"zod\";\n *\n * const approve = defineAction({\n * name: \"approve\",\n * schema: z.object({ reason: z.string() }),\n * });\n * const reject = defineAction({\n * name: \"reject\",\n * schema: z.object({ reason: z.string() }),\n * });\n *\n * const outputSchema = buildActionOutputSchema([approve, reject]);\n * // Accepts: { action: \"approve\", reason: \"...\" }\n * // or: { action: \"reject\", reason: \"...\" }\n * ```\n */\nexport const buildActionOutputSchema = (actions: PlatformAction[]) => {\n if (actions.length === 0) {\n throw new Error(\"Cannot build output schema from empty action definitions\");\n }\n\n const variants = actions.map((action) =>\n z.object({ action: z.literal(action.name) }).extend(action.zodSchema.shape),\n );\n\n const [first, ...rest] = variants;\n if (!first) {\n throw new Error(\"Cannot build output schema from empty action definitions\");\n }\n return z.discriminatedUnion(\"action\", [first, ...rest]);\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nconst supportsColor =\n !(\"NO_COLOR\" in process.env) &&\n process.env.FORCE_COLOR !== \"0\" &&\n (process.stderr.isTTY ?? false);\n\nconst code = (open: number, close: number) => {\n const openStr = `\\x1b[${open}m`;\n const closeStr = `\\x1b[${close}m`;\n return (s: string): string => (supportsColor ? `${openStr}${s}${closeStr}` : s);\n};\n\nexport const bold = code(1, 22);\nexport const dim = code(2, 22);\nexport const red = code(31, 39);\nexport const yellow = code(33, 39);\nexport const green = code(32, 39);\nexport const cyan = code(36, 39);\n\nexport const info = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${cyan(\"info\")}${dim(\"]\")} ${msg}\\n`);\n};\n\nexport const warn = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${yellow(\"warn\")}${dim(\"]\")} ${msg}\\n`);\n};\n\nexport const error = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${red(\"error\")}${dim(\"]\")} ${msg}\\n`);\n};\n\nexport const success = (msg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