@kraken-ai/platform 0.0.1 → 0.0.2

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.cjs CHANGED
@@ -36,7 +36,6 @@ __export(index_exports, {
36
36
  ConnectorError: () => ConnectorError,
37
37
  MANIFEST_END: () => MANIFEST_END,
38
38
  MANIFEST_START: () => MANIFEST_START,
39
- MockToolSet: () => MockToolSet,
40
39
  PlatformClient: () => PlatformClient,
41
40
  PlatformError: () => PlatformError,
42
41
  SecurityError: () => SecurityError,
@@ -62,7 +61,6 @@ __export(index_exports, {
62
61
  projectManifestSchema: () => projectManifestSchema,
63
62
  resourceLimitsSchema: () => resourceLimitsSchema,
64
63
  retryPolicySchema: () => retryPolicySchema,
65
- runDev: () => runDev,
66
64
  teamConfigSchema: () => teamConfigSchema,
67
65
  triggerConfigSchema: () => triggerConfigSchema,
68
66
  wrapToolError: () => wrapToolError,
@@ -446,10 +444,6 @@ var yellow = code(33, 39);
446
444
  var green = code(32, 39);
447
445
  var cyan = code(36, 39);
448
446
 
449
- // src/cli/validate.ts
450
- var ENTITY_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;
451
- var isValidEntityName = (name) => name.length === 1 ? /^[a-z0-9]$/.test(name) : ENTITY_NAME_REGEX.test(name);
452
-
453
447
  // src/cli/discover.ts
454
448
  var MANIFEST_START = "---KRAKEN-MANIFEST-START---";
455
449
  var MANIFEST_END = "---KRAKEN-MANIFEST-END---";
@@ -493,444 +487,6 @@ var parseManifestFromOutput = (stdout) => {
493
487
  return result.data;
494
488
  };
495
489
 
496
- // src/dev.ts
497
- var import_node_fs2 = require("fs");
498
- var import_node_readline = require("readline");
499
- var import_kraken_ai2 = require("kraken-ai");
500
-
501
- // src/dev-actions.ts
502
- var buildActionInstructions = (zodSchemas) => {
503
- const entries = Object.entries(zodSchemas);
504
- if (entries.length === 0) return "";
505
- const variants = entries.map(([name, schema]) => {
506
- const fields = Object.keys(schema.shape).join(", ");
507
- return ` - "${name}": { ${fields} }`;
508
- });
509
- return [
510
- 'You MUST respond with a JSON object containing an "action" field set to one of the following action names, plus the fields for that action:',
511
- "",
512
- ...variants,
513
- "",
514
- 'Example: { "action": "<name>", ...fields }'
515
- ].join("\n");
516
- };
517
- var dispatchDevAction = async (output, zodSchemas, handlers, webhooks) => {
518
- if (output == null || typeof output !== "object" || !("action" in output)) {
519
- throw new Error('Action output must contain an "action" field');
520
- }
521
- const { action: actionName, ...rest } = output;
522
- if (typeof actionName !== "string") {
523
- throw new Error('Action output "action" field must be a string');
524
- }
525
- const schema = zodSchemas[actionName];
526
- if (!schema) {
527
- throw new Error(
528
- `Unknown action "${actionName}". Expected one of: ${Object.keys(zodSchemas).join(", ")}`
529
- );
530
- }
531
- const parsed = schema.parse(rest);
532
- const payload = parsed;
533
- let handlerCalled = false;
534
- const handler = handlers?.[actionName];
535
- if (handler) {
536
- await handler(payload);
537
- handlerCalled = true;
538
- }
539
- return {
540
- actionName,
541
- payload,
542
- handlerCalled,
543
- webhookUrl: webhooks[actionName]
544
- };
545
- };
546
-
547
- // src/dev-connectors.ts
548
- var import_node_path2 = require("path");
549
- var import_kraken_ai = require("kraken-ai");
550
- var isPlatformConnector2 = (v) => v != null && typeof v === "object" && v.__type === "PlatformConnector";
551
- var importConnector = async (name, projectRoot) => {
552
- const basePath = (0, import_node_path2.resolve)(projectRoot, "connectors", name, "index");
553
- for (const ext of [".ts", ".js"]) {
554
- try {
555
- const mod = await import(`${basePath}${ext}`);
556
- const connector = mod.default;
557
- if (!isPlatformConnector2(connector)) {
558
- console.warn(`[connector:${name}] Default export is not a PlatformConnector \u2014 skipping`);
559
- return null;
560
- }
561
- return connector;
562
- } catch (err) {
563
- if (ext === ".ts") continue;
564
- const message = err instanceof Error ? err.message : String(err);
565
- console.warn(`[connector:${name}] Failed to import \u2014 skipping. Error: ${message}`);
566
- return null;
567
- }
568
- }
569
- return null;
570
- };
571
- var createToolsFromConnector = (connector) => {
572
- const tools = connector.tools ?? {};
573
- return Object.entries(tools).map(
574
- ([name, def]) => (0, import_kraken_ai.tool)({
575
- name,
576
- description: def.description,
577
- parameters: def.input,
578
- execute: async (args) => {
579
- try {
580
- const result = await Promise.resolve(def.handler(args));
581
- return wrapToolResult(result);
582
- } catch (error) {
583
- return wrapToolError(error);
584
- }
585
- }
586
- })
587
- );
588
- };
589
- var buildConnectorTools = (connectors) => {
590
- const toolOwners = /* @__PURE__ */ new Map();
591
- for (const { name, connector } of connectors) {
592
- for (const toolName of Object.keys(connector.tools ?? {})) {
593
- const existing = toolOwners.get(toolName);
594
- if (existing) {
595
- throw new Error(
596
- `Tool name collision: "${toolName}" is defined by both connectors "${existing}" and "${name}". Rename one of the tools or use a unique prefix.`
597
- );
598
- }
599
- toolOwners.set(toolName, name);
600
- }
601
- }
602
- const resourceOwners = /* @__PURE__ */ new Map();
603
- for (const { name, connector } of connectors) {
604
- for (const resourceName of Object.keys(connector.resources ?? {})) {
605
- const existing = resourceOwners.get(resourceName);
606
- if (existing) {
607
- throw new Error(
608
- `Resource name collision: "${resourceName}" is defined by both connectors "${existing}" and "${name}". Rename one of the resources or use a unique prefix.`
609
- );
610
- }
611
- resourceOwners.set(resourceName, name);
612
- }
613
- }
614
- const promptOwners = /* @__PURE__ */ new Map();
615
- for (const { name, connector } of connectors) {
616
- for (const promptName of Object.keys(connector.prompts ?? {})) {
617
- const existing = promptOwners.get(promptName);
618
- if (existing) {
619
- throw new Error(
620
- `Prompt name collision: "${promptName}" is defined by both connectors "${existing}" and "${name}". Rename one of the prompts or use a unique prefix.`
621
- );
622
- }
623
- promptOwners.set(promptName, name);
624
- }
625
- }
626
- const allTools = [];
627
- const allResources = [];
628
- const allPrompts = [];
629
- const allInstructions = [];
630
- for (const { name, connector } of connectors) {
631
- const tools = createToolsFromConnector(connector);
632
- allTools.push(...tools);
633
- for (const [resName, resDef] of Object.entries(connector.resources ?? {})) {
634
- allResources.push({
635
- name: resName,
636
- uri: resDef.uri,
637
- description: resDef.description,
638
- mimeType: resDef.mimeType,
639
- read: (ctx) => resDef.read(ctx)
640
- });
641
- }
642
- for (const [promptName, promptDef] of Object.entries(connector.prompts ?? {})) {
643
- allPrompts.push({
644
- name: promptName,
645
- description: promptDef.description,
646
- arguments: promptDef.arguments,
647
- get: (args, ctx) => promptDef.get(args, ctx)
648
- });
649
- }
650
- const toolCount = Object.keys(connector.tools ?? {}).length;
651
- const resourceCount = Object.keys(connector.resources ?? {}).length;
652
- const promptCount = Object.keys(connector.prompts ?? {}).length;
653
- const parts = [
654
- `${toolCount} tool${toolCount !== 1 ? "s" : ""}`,
655
- `${resourceCount} resource${resourceCount !== 1 ? "s" : ""}`,
656
- `${promptCount} prompt${promptCount !== 1 ? "s" : ""}`
657
- ];
658
- console.log(` Connector: ${name} (${parts.join(", ")})`);
659
- if (connector.instructions) {
660
- allInstructions.push(connector.instructions);
661
- }
662
- }
663
- return {
664
- tools: allTools,
665
- resources: allResources,
666
- prompts: allPrompts,
667
- instructions: allInstructions
668
- };
669
- };
670
- var loadConnectorTools = async (connectorNames, projectRoot) => {
671
- if (connectorNames.length === 0) {
672
- return { tools: [], resources: [], prompts: [], instructions: [] };
673
- }
674
- const root = projectRoot ?? process.cwd();
675
- const connectors = [];
676
- for (const name of connectorNames) {
677
- if (!isValidEntityName(name)) {
678
- console.warn(
679
- `[connector] Invalid connector name "${name}" \u2014 must match ${ENTITY_NAME_REGEX}. Skipping.`
680
- );
681
- continue;
682
- }
683
- const connector = await importConnector(name, root);
684
- if (connector) {
685
- connectors.push({ name, connector });
686
- }
687
- }
688
- return buildConnectorTools(connectors);
689
- };
690
-
691
- // src/dev.ts
692
- var loadDotenv = () => {
693
- try {
694
- const content = (0, import_node_fs2.readFileSync)(".env", "utf-8");
695
- for (const line of content.split("\n")) {
696
- const trimmed = line.trim();
697
- if (!trimmed || trimmed.startsWith("#")) continue;
698
- const eqIdx = trimmed.indexOf("=");
699
- if (eqIdx === -1) continue;
700
- const key = trimmed.slice(0, eqIdx).trim();
701
- const value = trimmed.slice(eqIdx + 1).trim();
702
- if (!process.env[key]) {
703
- process.env[key] = value;
704
- }
705
- }
706
- } catch {
707
- }
708
- };
709
- var FRONTMATTER_RE = /^---\n[\s\S]*?\n---\n([\s\S]*)$/;
710
- var resolveSkillContent = (refs) => refs.map((ref) => {
711
- try {
712
- return (0, import_node_fs2.readFileSync)(`skills/${ref}`, "utf-8");
713
- } catch {
714
- return ref;
715
- }
716
- });
717
- var buildInstructions = (base, skillContent) => {
718
- if (skillContent.length === 0) return base;
719
- const bodies = skillContent.map((s) => {
720
- const m = FRONTMATTER_RE.exec(s);
721
- return m?.[1]?.trim() ?? s;
722
- });
723
- return `${base}
724
-
725
- ${bodies.join("\n\n")}`;
726
- };
727
- var buildDevAgent = async (pa) => {
728
- const {
729
- name,
730
- model,
731
- instructions,
732
- skills,
733
- temperature,
734
- thinkingLevel,
735
- maxOutputTokens,
736
- logLevel
737
- } = pa.config.agent;
738
- const connectorNames = pa.config.connectors ?? [];
739
- const { tools: connectorTools, instructions: connectorInstructions } = await loadConnectorTools(connectorNames);
740
- const skillContent = resolveSkillContent(skills ?? []);
741
- let fullInstructions = buildInstructions(instructions, skillContent);
742
- if (connectorInstructions.length > 0) {
743
- fullInstructions = `${fullInstructions}
744
-
745
- ${connectorInstructions.join("\n\n")}`;
746
- }
747
- let outputSchema;
748
- if (pa.actionZodSchemas && Object.keys(pa.actionZodSchemas).length > 0) {
749
- const actionInstructions = buildActionInstructions(pa.actionZodSchemas);
750
- if (actionInstructions) {
751
- fullInstructions = `${fullInstructions}
752
-
753
- ${actionInstructions}`;
754
- }
755
- outputSchema = buildActionOutputSchema({
756
- __type: "PlatformActions",
757
- config: pa.config.actions ?? { variants: {} },
758
- zodSchemas: pa.actionZodSchemas,
759
- handlers: pa.actionHandlers ?? {}
760
- });
761
- }
762
- let team;
763
- if (pa.teamAgents && pa.teamAgents.length > 0) {
764
- team = await Promise.all(pa.teamAgents.map(buildDevAgent));
765
- }
766
- return new import_kraken_ai2.Agent({
767
- name,
768
- model,
769
- instructions: fullInstructions,
770
- tools: connectorTools.length > 0 ? connectorTools : void 0,
771
- outputSchema,
772
- team,
773
- temperature,
774
- thinkingLevel,
775
- maxOutputTokens,
776
- logLevel
777
- });
778
- };
779
- var runDev = async (agent) => {
780
- loadDotenv();
781
- const hasActions = agent.actionZodSchemas && Object.keys(agent.actionZodSchemas).length > 0;
782
- const sdkAgent = await buildDevAgent(agent);
783
- const { name, model } = agent.config.agent;
784
- const connectorNames = agent.config.connectors ?? [];
785
- try {
786
- await sdkAgent.preflight();
787
- } catch (err) {
788
- console.error(`
789
- ${err instanceof Error ? err.message : String(err)}
790
- `);
791
- process.exit(1);
792
- }
793
- console.log(`
794
- Agent: ${name}`);
795
- console.log(` Model: ${model}`);
796
- if (connectorNames.length > 0) {
797
- console.log(` Connectors: ${connectorNames.join(", ")}`);
798
- }
799
- if (agent.teamAgents && agent.teamAgents.length > 0) {
800
- console.log(` Team: ${agent.teamAgents.map((a) => a.config.agent.name).join(", ")}`);
801
- }
802
- if (hasActions && agent.actionZodSchemas) {
803
- console.log(` Actions: ${Object.keys(agent.actionZodSchemas).join(", ")}`);
804
- }
805
- console.log(`
806
- Type a message to start. Ctrl+C to exit.
807
- `);
808
- const rl = (0, import_node_readline.createInterface)({ input: process.stdin, output: process.stdout });
809
- const messages = [];
810
- const cleanup = () => {
811
- rl.close();
812
- process.exit(0);
813
- };
814
- process.on("SIGINT", cleanup);
815
- process.on("SIGTERM", cleanup);
816
- const ask = () => {
817
- rl.question("You: ", (input) => {
818
- if (!input.trim()) {
819
- ask();
820
- return;
821
- }
822
- messages.push({ role: "user", content: input });
823
- void (async () => {
824
- try {
825
- const result = await sdkAgent.run(messages, {
826
- onEvent: (event) => {
827
- if (event.type === "thought") {
828
- console.log(
829
- ` [thinking] ${event.text.slice(0, 120)}${event.text.length > 120 ? "\u2026" : ""}`
830
- );
831
- }
832
- if (event.type === "tool_call" && event.status === "success") {
833
- console.log(` [tool] ${event.toolName}`);
834
- }
835
- }
836
- });
837
- if (result.status === "complete") {
838
- const output = typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2);
839
- if (hasActions && agent.actionZodSchemas && result.output != null && typeof result.output === "object" && "action" in result.output) {
840
- const webhooks = {};
841
- if (agent.config.actions?.variants) {
842
- for (const [k, v] of Object.entries(agent.config.actions.variants)) {
843
- webhooks[k] = v.webhook;
844
- }
845
- }
846
- try {
847
- const dispatched = await dispatchDevAction(
848
- result.output,
849
- agent.actionZodSchemas,
850
- agent.actionHandlers,
851
- webhooks
852
- );
853
- console.log(`
854
- ${cyan("Action:")} ${green(dispatched.actionName)}`);
855
- console.log(` ${dim("Payload:")} ${JSON.stringify(dispatched.payload, null, 2)}`);
856
- if (dispatched.handlerCalled) {
857
- console.log(` ${dim("Handler:")} ${green("called")}`);
858
- }
859
- if (dispatched.webhookUrl) {
860
- console.log(
861
- ` ${dim("Webhook:")} ${yellow(dispatched.webhookUrl)} ${dim("(skipped in dev)")}`
862
- );
863
- }
864
- console.log();
865
- } catch (err) {
866
- console.error(
867
- `
868
- Action dispatch error: ${err instanceof Error ? err.message : String(err)}
869
- `
870
- );
871
- }
872
- } else {
873
- console.log(`
874
- Agent: ${output}
875
- `);
876
- }
877
- messages.push({ role: "assistant", content: output });
878
- } else if (result.status === "interrupted") {
879
- console.log(`
880
- [Interrupted: ${result.interrupt.toolName} requires approval]
881
- `);
882
- }
883
- } catch (err) {
884
- console.error(`
885
- Error: ${err instanceof Error ? err.message : String(err)}
886
- `);
887
- }
888
- ask();
889
- })();
890
- });
891
- };
892
- ask();
893
- return new Promise(() => {
894
- });
895
- };
896
-
897
- // src/mock-tool-set.ts
898
- var MockToolSet = class _MockToolSet {
899
- defs;
900
- overrides;
901
- toolNames;
902
- constructor(tools, overrides = {}) {
903
- this.defs = tools;
904
- this.overrides = overrides;
905
- this.toolNames = new Set(tools.map((t) => t.name));
906
- }
907
- static fromConnectors(connectors, opts) {
908
- const include = opts?.include;
909
- const filtered = include ? connectors.filter((c) => include.includes(c.id)) : connectors;
910
- const tools = filtered.flatMap(
911
- (c) => c.tools.map((t) => ({
912
- name: t.name,
913
- description: t.description,
914
- parameters: t.parameters
915
- }))
916
- );
917
- return new _MockToolSet(tools, opts?.overrides);
918
- }
919
- definitions() {
920
- return this.defs;
921
- }
922
- async call(name, params) {
923
- if (!this.toolNames.has(name)) {
924
- throw new Error(`Unknown tool: ${name}`);
925
- }
926
- const override = this.overrides[name];
927
- if (override) {
928
- return override(params);
929
- }
930
- return {};
931
- }
932
- };
933
-
934
490
  // src/platform/http.ts
935
491
  var PlatformError = class extends Error {
936
492
  constructor(message, status) {
@@ -1061,13 +617,13 @@ var parseBlock = (block) => {
1061
617
 
1062
618
  // src/platform/agent-handle.ts
1063
619
  var deferred = () => {
1064
- let resolve2;
620
+ let resolve;
1065
621
  let reject;
1066
622
  const promise = new Promise((res, rej) => {
1067
- resolve2 = res;
623
+ resolve = res;
1068
624
  reject = rej;
1069
625
  });
1070
- return { promise, resolve: resolve2, reject };
626
+ return { promise, resolve, reject };
1071
627
  };
1072
628
  var AgentHandle = class {
1073
629
  constructor(http, agentId, opts) {
@@ -1346,7 +902,6 @@ var PlatformClient = class {
1346
902
  ConnectorError,
1347
903
  MANIFEST_END,
1348
904
  MANIFEST_START,
1349
- MockToolSet,
1350
905
  PlatformClient,
1351
906
  PlatformError,
1352
907
  SecurityError,
@@ -1372,7 +927,6 @@ var PlatformClient = class {
1372
927
  projectManifestSchema,
1373
928
  resourceLimitsSchema,
1374
929
  retryPolicySchema,
1375
- runDev,
1376
930
  teamConfigSchema,
1377
931
  triggerConfigSchema,
1378
932
  wrapToolError,