@perstack/runtime 0.0.4 → 0.0.6
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.d.ts +40 -0
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -4
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
22
22
|
pick: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
23
23
|
omit: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
24
24
|
command: z.ZodString;
|
|
25
|
+
packageName: z.ZodOptional<z.ZodString>;
|
|
25
26
|
args: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
26
27
|
requiredEnv: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
27
28
|
}, "strip", z.ZodTypeAny, {
|
|
@@ -32,6 +33,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
32
33
|
rule?: string | undefined;
|
|
33
34
|
pick?: string[] | undefined;
|
|
34
35
|
omit?: string[] | undefined;
|
|
36
|
+
packageName?: string | undefined;
|
|
35
37
|
requiredEnv?: string[] | undefined;
|
|
36
38
|
}, {
|
|
37
39
|
type: "mcpStdioSkill";
|
|
@@ -41,6 +43,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
41
43
|
rule?: string | undefined;
|
|
42
44
|
pick?: string[] | undefined;
|
|
43
45
|
omit?: string[] | undefined;
|
|
46
|
+
packageName?: string | undefined;
|
|
44
47
|
requiredEnv?: string[] | undefined;
|
|
45
48
|
}>, z.ZodObject<{
|
|
46
49
|
type: z.ZodLiteral<"mcpSseSkill">;
|
|
@@ -107,6 +110,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
107
110
|
rule?: string | undefined;
|
|
108
111
|
pick?: string[] | undefined;
|
|
109
112
|
omit?: string[] | undefined;
|
|
113
|
+
packageName?: string | undefined;
|
|
110
114
|
requiredEnv?: string[] | undefined;
|
|
111
115
|
} | {
|
|
112
116
|
type: "mcpSseSkill";
|
|
@@ -138,6 +142,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
138
142
|
rule?: string | undefined;
|
|
139
143
|
pick?: string[] | undefined;
|
|
140
144
|
omit?: string[] | undefined;
|
|
145
|
+
packageName?: string | undefined;
|
|
141
146
|
requiredEnv?: string[] | undefined;
|
|
142
147
|
} | {
|
|
143
148
|
type: "mcpSseSkill";
|
|
@@ -171,6 +176,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
171
176
|
rule?: string | undefined;
|
|
172
177
|
pick?: string[] | undefined;
|
|
173
178
|
omit?: string[] | undefined;
|
|
179
|
+
packageName?: string | undefined;
|
|
174
180
|
requiredEnv?: string[] | undefined;
|
|
175
181
|
} | {
|
|
176
182
|
type: "mcpSseSkill";
|
|
@@ -208,6 +214,7 @@ declare const PerstackConfigSchema: z.ZodObject<{
|
|
|
208
214
|
rule?: string | undefined;
|
|
209
215
|
pick?: string[] | undefined;
|
|
210
216
|
omit?: string[] | undefined;
|
|
217
|
+
packageName?: string | undefined;
|
|
211
218
|
requiredEnv?: string[] | undefined;
|
|
212
219
|
} | {
|
|
213
220
|
type: "mcpSseSkill";
|
|
@@ -1311,6 +1318,7 @@ declare const McpStdioSkillSchema: z.ZodObject<{
|
|
|
1311
1318
|
pick: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1312
1319
|
omit: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1313
1320
|
command: z.ZodString;
|
|
1321
|
+
packageName: z.ZodOptional<z.ZodString>;
|
|
1314
1322
|
args: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1315
1323
|
requiredEnv: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1316
1324
|
}, "strip", z.ZodTypeAny, {
|
|
@@ -1323,6 +1331,7 @@ declare const McpStdioSkillSchema: z.ZodObject<{
|
|
|
1323
1331
|
requiredEnv: string[];
|
|
1324
1332
|
description?: string | undefined;
|
|
1325
1333
|
rule?: string | undefined;
|
|
1334
|
+
packageName?: string | undefined;
|
|
1326
1335
|
}, {
|
|
1327
1336
|
type: "mcpStdioSkill";
|
|
1328
1337
|
name: string;
|
|
@@ -1332,6 +1341,7 @@ declare const McpStdioSkillSchema: z.ZodObject<{
|
|
|
1332
1341
|
rule?: string | undefined;
|
|
1333
1342
|
pick?: string[] | undefined;
|
|
1334
1343
|
omit?: string[] | undefined;
|
|
1344
|
+
packageName?: string | undefined;
|
|
1335
1345
|
requiredEnv?: string[] | undefined;
|
|
1336
1346
|
}>;
|
|
1337
1347
|
type McpStdioSkill = z.infer<typeof McpStdioSkillSchema>;
|
|
@@ -1436,6 +1446,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1436
1446
|
pick: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1437
1447
|
omit: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1438
1448
|
command: z.ZodString;
|
|
1449
|
+
packageName: z.ZodOptional<z.ZodString>;
|
|
1439
1450
|
args: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1440
1451
|
requiredEnv: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
1441
1452
|
}, "name">, "strip", z.ZodTypeAny, {
|
|
@@ -1447,6 +1458,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1447
1458
|
requiredEnv: string[];
|
|
1448
1459
|
description?: string | undefined;
|
|
1449
1460
|
rule?: string | undefined;
|
|
1461
|
+
packageName?: string | undefined;
|
|
1450
1462
|
}, {
|
|
1451
1463
|
type: "mcpStdioSkill";
|
|
1452
1464
|
command: string;
|
|
@@ -1455,6 +1467,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1455
1467
|
rule?: string | undefined;
|
|
1456
1468
|
pick?: string[] | undefined;
|
|
1457
1469
|
omit?: string[] | undefined;
|
|
1470
|
+
packageName?: string | undefined;
|
|
1458
1471
|
requiredEnv?: string[] | undefined;
|
|
1459
1472
|
}>, z.ZodObject<Omit<{
|
|
1460
1473
|
type: z.ZodLiteral<"mcpSseSkill">;
|
|
@@ -1533,6 +1546,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1533
1546
|
requiredEnv: string[];
|
|
1534
1547
|
description?: string | undefined;
|
|
1535
1548
|
rule?: string | undefined;
|
|
1549
|
+
packageName?: string | undefined;
|
|
1536
1550
|
} | {
|
|
1537
1551
|
type: "mcpSseSkill";
|
|
1538
1552
|
name: string;
|
|
@@ -1562,6 +1576,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1562
1576
|
rule?: string | undefined;
|
|
1563
1577
|
pick?: string[] | undefined;
|
|
1564
1578
|
omit?: string[] | undefined;
|
|
1579
|
+
packageName?: string | undefined;
|
|
1565
1580
|
requiredEnv?: string[] | undefined;
|
|
1566
1581
|
} | {
|
|
1567
1582
|
type: "mcpSseSkill";
|
|
@@ -1597,6 +1612,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1597
1612
|
requiredEnv: string[];
|
|
1598
1613
|
description?: string | undefined;
|
|
1599
1614
|
rule?: string | undefined;
|
|
1615
|
+
packageName?: string | undefined;
|
|
1600
1616
|
} | {
|
|
1601
1617
|
type: "mcpSseSkill";
|
|
1602
1618
|
name: string;
|
|
@@ -1636,6 +1652,7 @@ declare const ExpertSchema: z.ZodObject<{
|
|
|
1636
1652
|
rule?: string | undefined;
|
|
1637
1653
|
pick?: string[] | undefined;
|
|
1638
1654
|
omit?: string[] | undefined;
|
|
1655
|
+
packageName?: string | undefined;
|
|
1639
1656
|
requiredEnv?: string[] | undefined;
|
|
1640
1657
|
} | {
|
|
1641
1658
|
type: "mcpSseSkill";
|
|
@@ -2497,6 +2514,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2497
2514
|
pick: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
2498
2515
|
omit: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
2499
2516
|
command: z.ZodString;
|
|
2517
|
+
packageName: z.ZodOptional<z.ZodString>;
|
|
2500
2518
|
args: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
2501
2519
|
requiredEnv: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
2502
2520
|
}, "name">, "strip", z.ZodTypeAny, {
|
|
@@ -2508,6 +2526,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2508
2526
|
requiredEnv: string[];
|
|
2509
2527
|
description?: string | undefined;
|
|
2510
2528
|
rule?: string | undefined;
|
|
2529
|
+
packageName?: string | undefined;
|
|
2511
2530
|
}, {
|
|
2512
2531
|
type: "mcpStdioSkill";
|
|
2513
2532
|
command: string;
|
|
@@ -2516,6 +2535,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2516
2535
|
rule?: string | undefined;
|
|
2517
2536
|
pick?: string[] | undefined;
|
|
2518
2537
|
omit?: string[] | undefined;
|
|
2538
|
+
packageName?: string | undefined;
|
|
2519
2539
|
requiredEnv?: string[] | undefined;
|
|
2520
2540
|
}>, z.ZodObject<Omit<{
|
|
2521
2541
|
type: z.ZodLiteral<"mcpSseSkill">;
|
|
@@ -2594,6 +2614,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2594
2614
|
requiredEnv: string[];
|
|
2595
2615
|
description?: string | undefined;
|
|
2596
2616
|
rule?: string | undefined;
|
|
2617
|
+
packageName?: string | undefined;
|
|
2597
2618
|
} | {
|
|
2598
2619
|
type: "mcpSseSkill";
|
|
2599
2620
|
name: string;
|
|
@@ -2623,6 +2644,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2623
2644
|
rule?: string | undefined;
|
|
2624
2645
|
pick?: string[] | undefined;
|
|
2625
2646
|
omit?: string[] | undefined;
|
|
2647
|
+
packageName?: string | undefined;
|
|
2626
2648
|
requiredEnv?: string[] | undefined;
|
|
2627
2649
|
} | {
|
|
2628
2650
|
type: "mcpSseSkill";
|
|
@@ -2657,6 +2679,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2657
2679
|
requiredEnv: string[];
|
|
2658
2680
|
description?: string | undefined;
|
|
2659
2681
|
rule?: string | undefined;
|
|
2682
|
+
packageName?: string | undefined;
|
|
2660
2683
|
} | {
|
|
2661
2684
|
type: "mcpSseSkill";
|
|
2662
2685
|
name: string;
|
|
@@ -2695,6 +2718,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2695
2718
|
rule?: string | undefined;
|
|
2696
2719
|
pick?: string[] | undefined;
|
|
2697
2720
|
omit?: string[] | undefined;
|
|
2721
|
+
packageName?: string | undefined;
|
|
2698
2722
|
requiredEnv?: string[] | undefined;
|
|
2699
2723
|
} | {
|
|
2700
2724
|
type: "mcpSseSkill";
|
|
@@ -2731,6 +2755,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2731
2755
|
requiredEnv: string[];
|
|
2732
2756
|
description?: string | undefined;
|
|
2733
2757
|
rule?: string | undefined;
|
|
2758
|
+
packageName?: string | undefined;
|
|
2734
2759
|
} | {
|
|
2735
2760
|
type: "mcpSseSkill";
|
|
2736
2761
|
name: string;
|
|
@@ -2770,6 +2795,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2770
2795
|
rule?: string | undefined;
|
|
2771
2796
|
pick?: string[] | undefined;
|
|
2772
2797
|
omit?: string[] | undefined;
|
|
2798
|
+
packageName?: string | undefined;
|
|
2773
2799
|
requiredEnv?: string[] | undefined;
|
|
2774
2800
|
} | {
|
|
2775
2801
|
type: "mcpSseSkill";
|
|
@@ -2826,6 +2852,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2826
2852
|
requiredEnv: string[];
|
|
2827
2853
|
description?: string | undefined;
|
|
2828
2854
|
rule?: string | undefined;
|
|
2855
|
+
packageName?: string | undefined;
|
|
2829
2856
|
} | {
|
|
2830
2857
|
type: "mcpSseSkill";
|
|
2831
2858
|
name: string;
|
|
@@ -2884,6 +2911,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
2884
2911
|
rule?: string | undefined;
|
|
2885
2912
|
pick?: string[] | undefined;
|
|
2886
2913
|
omit?: string[] | undefined;
|
|
2914
|
+
packageName?: string | undefined;
|
|
2887
2915
|
requiredEnv?: string[] | undefined;
|
|
2888
2916
|
} | {
|
|
2889
2917
|
type: "mcpSseSkill";
|
|
@@ -3711,6 +3739,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
3711
3739
|
requiredEnv: string[];
|
|
3712
3740
|
description?: string | undefined;
|
|
3713
3741
|
rule?: string | undefined;
|
|
3742
|
+
packageName?: string | undefined;
|
|
3714
3743
|
} | {
|
|
3715
3744
|
type: "mcpSseSkill";
|
|
3716
3745
|
name: string;
|
|
@@ -3894,6 +3923,7 @@ declare const RunParamsSchema: z.ZodObject<{
|
|
|
3894
3923
|
rule?: string | undefined;
|
|
3895
3924
|
pick?: string[] | undefined;
|
|
3896
3925
|
omit?: string[] | undefined;
|
|
3926
|
+
packageName?: string | undefined;
|
|
3897
3927
|
requiredEnv?: string[] | undefined;
|
|
3898
3928
|
} | {
|
|
3899
3929
|
type: "mcpSseSkill";
|
|
@@ -5030,6 +5060,7 @@ declare const runtimeStateMachine: xstate.StateMachine<{
|
|
|
5030
5060
|
requiredEnv: string[];
|
|
5031
5061
|
description?: string | undefined;
|
|
5032
5062
|
rule?: string | undefined;
|
|
5063
|
+
packageName?: string | undefined;
|
|
5033
5064
|
} | {
|
|
5034
5065
|
type: "mcpSseSkill";
|
|
5035
5066
|
name: string;
|
|
@@ -9402,6 +9433,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9402
9433
|
pick: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
9403
9434
|
omit: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
9404
9435
|
command: z.ZodString;
|
|
9436
|
+
packageName: z.ZodOptional<z.ZodString>;
|
|
9405
9437
|
args: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
9406
9438
|
requiredEnv: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
|
|
9407
9439
|
}, "name">, "strip", z.ZodTypeAny, {
|
|
@@ -9413,6 +9445,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9413
9445
|
requiredEnv: string[];
|
|
9414
9446
|
description?: string | undefined;
|
|
9415
9447
|
rule?: string | undefined;
|
|
9448
|
+
packageName?: string | undefined;
|
|
9416
9449
|
}, {
|
|
9417
9450
|
type: "mcpStdioSkill";
|
|
9418
9451
|
command: string;
|
|
@@ -9421,6 +9454,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9421
9454
|
rule?: string | undefined;
|
|
9422
9455
|
pick?: string[] | undefined;
|
|
9423
9456
|
omit?: string[] | undefined;
|
|
9457
|
+
packageName?: string | undefined;
|
|
9424
9458
|
requiredEnv?: string[] | undefined;
|
|
9425
9459
|
}>, z.ZodObject<Omit<{
|
|
9426
9460
|
type: z.ZodLiteral<"mcpSseSkill">;
|
|
@@ -9516,6 +9550,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9516
9550
|
requiredEnv: string[];
|
|
9517
9551
|
description?: string | undefined;
|
|
9518
9552
|
rule?: string | undefined;
|
|
9553
|
+
packageName?: string | undefined;
|
|
9519
9554
|
} | {
|
|
9520
9555
|
type: "mcpSseSkill";
|
|
9521
9556
|
pick: string[];
|
|
@@ -9557,6 +9592,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9557
9592
|
rule?: string | undefined;
|
|
9558
9593
|
pick?: string[] | undefined;
|
|
9559
9594
|
omit?: string[] | undefined;
|
|
9595
|
+
packageName?: string | undefined;
|
|
9560
9596
|
requiredEnv?: string[] | undefined;
|
|
9561
9597
|
} | {
|
|
9562
9598
|
type: "mcpSseSkill";
|
|
@@ -9599,6 +9635,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9599
9635
|
requiredEnv: string[];
|
|
9600
9636
|
description?: string | undefined;
|
|
9601
9637
|
rule?: string | undefined;
|
|
9638
|
+
packageName?: string | undefined;
|
|
9602
9639
|
} | {
|
|
9603
9640
|
type: "mcpSseSkill";
|
|
9604
9641
|
pick: string[];
|
|
@@ -9642,6 +9679,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9642
9679
|
rule?: string | undefined;
|
|
9643
9680
|
pick?: string[] | undefined;
|
|
9644
9681
|
omit?: string[] | undefined;
|
|
9682
|
+
packageName?: string | undefined;
|
|
9645
9683
|
requiredEnv?: string[] | undefined;
|
|
9646
9684
|
} | {
|
|
9647
9685
|
type: "mcpSseSkill";
|
|
@@ -9686,6 +9724,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9686
9724
|
requiredEnv: string[];
|
|
9687
9725
|
description?: string | undefined;
|
|
9688
9726
|
rule?: string | undefined;
|
|
9727
|
+
packageName?: string | undefined;
|
|
9689
9728
|
} | {
|
|
9690
9729
|
type: "mcpSseSkill";
|
|
9691
9730
|
pick: string[];
|
|
@@ -9731,6 +9770,7 @@ declare const RegistryV1ExpertsGetResponseSchema: z.ZodObject<{
|
|
|
9731
9770
|
rule?: string | undefined;
|
|
9732
9771
|
pick?: string[] | undefined;
|
|
9733
9772
|
omit?: string[] | undefined;
|
|
9773
|
+
packageName?: string | undefined;
|
|
9734
9774
|
requiredEnv?: string[] | undefined;
|
|
9735
9775
|
} | {
|
|
9736
9776
|
type: "mcpSseSkill";
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {existsSync}from'fs';import {readFile,writeFile,mkdir,readdir}from'fs/promises';import pe from'path';import {createId}from'@paralleldrive/cuid2';import To from'smol-toml';import {setup,assign,createActor}from'xstate';import {z as z$1,ZodError}from'zod';import {anthropic}from'@ai-sdk/anthropic';import {google}from'@ai-sdk/google';import {openai}from'@ai-sdk/openai';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {SSEClientTransport}from'@modelcontextprotocol/sdk/client/sse.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {McpError}from'@modelcontextprotocol/sdk/types.js';import {generateText,jsonSchema}from'ai';import {dedent}from'ts-dedent';var ft="claude-4-sonnet-20250514",ue=["claude-4-opus-20250514","claude-4-sonnet-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-latest","claude-3-5-sonnet-20241022","claude-3-5-sonnet-20240620","claude-3-5-haiku-latest","claude-3-5-haiku-20241022"],ge=["gemini-2.5-pro-preview-05-06","gemini-2.5-pro-exp-03-25","gemini-2.5-flash-preview-04-17","gemini-2.0-pro-exp-02-05","gemini-2.0-flash-thinking-exp-01-21","gemini-2.0-flash","gemini-2.0-flash-001","gemini-2.0-flash-live-001","gemini-2.0-flash-lite","gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-pro-latest","gemini-1.5-pro-001","gemini-1.5-pro-002","gemini-1.5-flash","gemini-1.5-flash-latest","gemini-1.5-flash-001","gemini-1.5-flash-002","gemini-1.5-flash-8b","gemini-1.5-flash-8b-latest","gemini-1.5-flash-8b-001"],de=["o4-mini","o4-mini-2025-04-16","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18"],ht=Object.fromEntries([...ue,...ge,...de].map(e=>[e,{default:e===ft,model:e}]));function te(){let e=Object.values(ht).find(t=>t.default);if(!e)throw new Error("No default model found");return e.model}function L(e){let t=e??te();if(ue.includes(t))return anthropic(t);if(ge.includes(t))return google(t);if(de.includes(t))return openai(t);throw new Error(`Unsupported model: ${t}`)}var I=z$1.object({id:z$1.string()}),_=I.extend({type:z$1.literal("textPart"),text:z$1.string()}),yt=I.extend({type:z$1.literal("imageUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),fe=I.extend({type:z$1.literal("imageInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),xt=I.extend({type:z$1.literal("imageBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),Tt=I.extend({type:z$1.literal("fileUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),kt=I.extend({type:z$1.literal("fileInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),Rt=I.extend({type:z$1.literal("fileBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),St=I.extend({type:z$1.literal("toolCallPart"),toolCallId:z$1.string(),toolName:z$1.string(),args:z$1.unknown()}),Pt=I.extend({type:z$1.literal("toolResultPart"),toolCallId:z$1.string(),toolName:z$1.string(),contents:z$1.array(z$1.union([_,fe])),isError:z$1.boolean().optional()}),A=z$1.object({id:z$1.string()}),vt=A.extend({type:z$1.literal("instructionMessage"),contents:z$1.array(_),cache:z$1.boolean().optional()}),Ct=A.extend({type:z$1.literal("userMessage"),contents:z$1.array(z$1.union([_,yt,fe,xt,Tt,kt,Rt])),cache:z$1.boolean().optional()}),wt=A.extend({type:z$1.literal("expertMessage"),contents:z$1.array(z$1.union([_,St])),cache:z$1.boolean().optional()}),It=A.extend({type:z$1.literal("toolMessage"),contents:z$1.array(Pt),cache:z$1.boolean().optional()}),he=z$1.union([vt,Ct,wt,It]);var Mt=/^(@[a-z0-9][a-z0-9_-]*\/)?[a-z0-9][a-z0-9_-]*$/,bt=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/,Et=/^[a-z0-9][a-z0-9_-]*$/,D=/^((?:@[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_\.-]*))?$/,Uo=/^[a-z0-9][a-z0-9._-]*$/,$t=214;function jo(e){let t=e.match(D);if(!t)throw new Error(`Invalid expert key format: ${e}`);let[o,r,a,c]=t;return {key:o,name:r,version:a,tag:c}}var G=z$1.object({type:z$1.literal("mcpStdioSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),command:z$1.string(),args:z$1.array(z$1.string()).optional().default([]),requiredEnv:z$1.array(z$1.string()).optional().default([])}),K=z$1.object({type:z$1.literal("mcpSseSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),endpoint:z$1.string()}),ye=z$1.object({name:z$1.string(),description:z$1.string().optional(),inputJsonSchema:z$1.string()}),q=z$1.object({type:z$1.literal("interactiveSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),tools:z$1.record(z$1.string(),ye.omit({name:true})).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,ye.parse({...o,name:t})])))}),J=z$1.object({key:z$1.string().regex(D).min(1),name:z$1.string().regex(Mt).min(1).max($t),version:z$1.string().regex(bt),description:z$1.string().min(1).max(1024*2).optional(),instruction:z$1.string().min(1).max(1024*20),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])).optional().default({"@perstack/base":{type:"mcpStdioSkill",description:"Base skill",command:"npx",args:["-y","@perstack/base"]}}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,z$1.discriminatedUnion("type",[G,K,q]).parse({...o,name:t})]))),delegates:z$1.array(z$1.string().regex(D).min(1)).optional().default([]),tags:z$1.array(z$1.string().regex(Et).min(1)).optional().default([])}),Nt=z$1.object({promptTokens:z$1.number(),completionTokens:z$1.number(),totalTokens:z$1.number(),cacheCreationInputTokens:z$1.number(),cacheReadInputTokens:z$1.number()}),Ft=z$1.enum(["init","proceeding","completed","stoppedByInteractiveTool","stoppedByDelegate","stoppedByExceededMaxSteps","stoppedByError"]),oe=z$1.object({id:z$1.string(),runId:z$1.string(),status:Ft,stepNumber:z$1.number(),messages:z$1.array(he),expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),delegateTo:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),query:z$1.string()}).optional(),delegatedBy:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),checkpointId:z$1.string()}).optional(),usage:Nt}),Te=z$1.object({setting:z$1.object({runId:z$1.string().optional().transform(e=>e??createId()),expertKey:z$1.string().regex(D).min(1),input:z$1.object({text:z$1.string().optional(),interactiveToolCallResult:z$1.object({toolCallId:z$1.string(),toolName:z$1.string(),text:z$1.string()}).optional()}),experts:z$1.record(z$1.string().regex(D).min(1),J.omit({key:true})).optional().default({}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,J.parse({...o,key:t})]))),model:z$1.string().optional().default(te()),temperature:z$1.number().min(0).max(1).optional().default(.3),maxSteps:z$1.number().min(1).optional(),maxRetries:z$1.number().min(0).optional().default(10),workspace:z$1.string().optional(),startedAt:z$1.number().optional().default(Date.now()),updatedAt:z$1.number().optional().default(Date.now())}),checkpoint:oe.optional()});function T(e){return (t,o,r)=>({type:e,id:createId(),expertKey:o.expert.key,timestamp:Date.now(),runId:t.runId,stepNumber:o.stepNumber,...r})}var ne=T("startRun"),ke=T("startGeneration"),re=T("retry"),Re=T("callTool"),Se=T("callInteractiveTool"),Pe=T("callDelegate"),ve=T("resolveToolResult"),Ce=T("resolveThought"),we=T("resolvePdfFile"),Ie=T("resolveImageFile"),Me=T("attemptCompletion"),$=T("finishToolCall"),be=T("completeRun"),Ee=T("stopRunByInteractiveTool"),$e=T("stopRunByDelegate"),Ne=T("stopRunByExceededMaxSteps"),Fe=T("continueToNextStep");async function De(e,t){let o=O(e),a=(await readdir(o,{withFileTypes:true}).then(s=>s.filter(u=>u.isFile()&&u.name.startsWith("checkpoint-")))).find(s=>s.name.endsWith(`-${t}.json`));if(!a)throw new Error(`checkpoint not found: ${e} ${t}`);let c=`${o}/${a.name}`,m=await readFile(c,"utf8");return oe.parse(JSON.parse(m))}async function Oe(e,t){let{id:o,runId:r,stepNumber:a}=e,c=O(r),m=`${c}/checkpoint-${t}-${a}-${o}.json`;await mkdir(c,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}async function Be(e){let{timestamp:t,runId:o,stepNumber:r,type:a}=e,c=O(o),m=`${c}/event-${t}-${r}-${a}.json`;await mkdir(c,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}var ze={version:"0.0.4"};var p=console.info,Le=console.debug,g=e=>{let t=new Date().toISOString(),o=e.stepNumber,r=e.expertKey;return `${t} ${o} ${r}`};async function se(e){switch(await Be(e),e.type){case "startRun":{p(`${g(e)} \u{1F99C} Perstack@${ze.version} started`);let{inputMessages:t}=e;for(let o of t)o.type==="userMessage"?Ot(o):o.type==="toolMessage"&&Bt(o);break}case "startGeneration":{p(`${g(e)} \u{1F99C} Generating tool call`);break}case "retry":{B(e),p(`${g(e)} \u{1F99C} Retrying tool call generation`);break}case "callTool":{if(B(e),p(`${g(e)} \u{1F99C} Calling tool`),e.toolCall.skillName==="@perstack/base")switch(e.toolCall.toolName){case "think":{let t=e.toolCall.args.thought;p(`${g(e)} \u{1F4AD} Thought Updated:`),Le(t);break}case "readPdfFile":{let t=e.toolCall.args.path;p(`${g(e)} \u{1F4C4} Reading PDF: ${t}`);break}case "readImageFile":{let t=e.toolCall.args.path;p(`${g(e)} \u{1F5BC}\uFE0F Reading Image: ${t}`);break}default:{p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}}else p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callInteractiveTool":{B(e),p(`${g(e)} \u{1F99C} Calling interactive tool`),p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callDelegate":{B(e),p(`${g(e)} \u{1F99C} Calling delegate`),p(`${g(e)} \u{1F527} Tool: ${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "resolveToolResult":{if(p(`${g(e)} \u{1F527} Resolved Tool Result`),e.toolResult.skillName==="@perstack/base")switch(e.toolResult.toolName){case "todo":{let t=e.toolResult.result.find(r=>r.type==="textPart")?.text,{todos:o}=JSON.parse(t??"{}");p(`${g(e)} \u{1F4C4} Todo:`);for(let r of o)Le(`${r.completed?"[x]":"[ ]"} ${r.id}: ${r.title}`);break}default:{p(`${g(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),p(`${g(e)} \u{1F527} Result: ${e.toolResult.result}`);break}}else p(`${g(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),p(`${g(e)} \u{1F527} Result: ${e.toolResult.result}`);break}case "resolveThought":{p(`${g(e)} \u{1F4AD} Resolved Thought:`,e.toolResult);break}case "resolvePdfFile":{p(`${g(e)} \u{1F4C4} Resolved PDF:`,e.toolResult);break}case "resolveImageFile":{p(`${g(e)} \u{1F5BC}\uFE0F Resolved Image:`,e.toolResult);break}case "attemptCompletion":{p(`${g(e)} \u2705 Attempting completion`);break}case "completeRun":{B(e),p(`${g(e)} \u{1F99C} Completing run`),p(`${g(e)} \u{1F99C} Result:`,e.text);break}case "stopRunByInteractiveTool":{p(`${g(e)} \u{1F99C} Stopping run by interactive tool`);break}case "stopRunByDelegate":{p(`${g(e)} \u{1F99C} Stopping run by delegate`);break}case "stopRunByExceededMaxSteps":{p(`${g(e)} \u{1F99C} Stopping run by exceeded max steps`);break}case "continueToNextStep":{p(`${g(e)} \u{1F99C} Continuing to next step`);break}}}function Ot(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)r.type==="textPart"?p(`${t} \u{1F4AC} User: ${r.text}`):r.type==="imageUrlPart"?p(`${t} \u{1F5BC}\uFE0F User: ${r.url}`):r.type==="imageInlinePart"?p(`${t} \u{1F5BC}\uFE0F User: Inline image`):r.type==="imageBinaryPart"?p(`${t} \u{1F5BC}\uFE0F User: Binary image`):r.type==="fileUrlPart"?p(`${t} \u{1F4C4} User: ${r.url}`):r.type==="fileInlinePart"?p(`${t} \u{1F4C4} User: Inline file`):r.type==="fileBinaryPart"&&p(`${t} \u{1F4C4} User: Binary file`);}function Bt(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)if(r.type==="toolResultPart"){let{contents:a}=r;for(let c of a)c.type==="textPart"?p(`${t} \u{1F4AC} Tool Result: ${c.text}`):c.type==="imageInlinePart"&&p(`${t} \u{1F5BC}\uFE0F Tool Result: Inline image`);}}function B(e){let t=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");p(`${g(e)} \u{1F4CA} Tokens usage: ${t}`);let o=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");p(`${g(e)} \u{1F4CA} Total usage: ${o}`);}var V=class{listeners=[];subscribe(t){this.listeners.push(t);}async emit(t){for(let o of this.listeners)await o({...t,id:createId(),timestamp:Date.now()});}};var Lt=z$1.object({name:z$1.string(),version:z$1.string(),minRuntimeVersion:z$1.string(),description:z$1.string(),instruction:z$1.string(),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])),delegates:z$1.array(z$1.string()),tags:z$1.array(z$1.string()),status:z$1.string(),owner:z$1.object({name:z$1.string()}),createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()}),_e=z$1.object({data:z$1.object({expert:Lt})});var Y=class{baseUrl;registry;apiKey;constructor(t){this.baseUrl=t?.baseUrl??process.env.PERSTACK_API_BASE_URL??"https://api.perstack.ai",this.apiKey=t?.apiKey??process.env.PERSTACK_API_KEY,this.registry=new ae(this);}},ae=class{client;endpoint;constructor(t){this.client=t,this.endpoint="/api/registry/v1/experts";}async get(t){let o=encodeURIComponent(t),r=new URL(`${this.endpoint}/${o}`,this.client.baseUrl),a={"Content-Type":"application/json",Authorization:`Bearer ${this.client.apiKey}`},c=await fetch(r.toString(),{headers:a});if(!c.ok)throw new Error(`Registry returned non-200 status code: ${c.status}, reason: ${c.statusText}`);let m=await c.json();return _e.parse(m)}};async function ie(e,t){if(t[e])return t[e];let o=new Y,{data:r}=await o.registry.get(e),a=J.parse({...r.expert,key:e});return t[e]=a,a}var z=class{_toolDefinitions=[];_initialized=false;name;type;skill;interactiveSkill;expert;_mcpClient;_params;constructor(t){switch(this._params=t,this.type=t.type,t.type){case "mcp":this.name=t.skill.name,this.skill=t.skill;break;case "interactive":this.name=t.interactiveSkill.name,this.interactiveSkill=t.interactiveSkill;break;case "delegate":this.name=t.expert.name,this.expert=t.expert;break}}async init(){switch(this._params.type){case "mcp":{await this._initMcpSkill(this._params);break}case "interactive":{await this._initInteractiveSkill(this._params);break}case "delegate":{await this._initDelegate(this._params);break}}}async _initMcpSkill(t){switch(this._mcpClient=new Client({name:`${t.skill.name}-mcp-client`,version:"1.0.0"}),t.skill.type){case "mcpStdioSkill":{if(!t.skill.command)throw new Error(`Skill ${t.skill.name} has no command`);let{command:r,args:a,requiredEnv:c}=t.skill,m=new StdioClientTransport({command:r,args:a,env:Object.fromEntries(Object.entries(process.env).filter(([s,u])=>u!==void 0&&u!=="").map(([s,u])=>[s,u]))});await this._mcpClient.connect(m);break}case "mcpSseSkill":{if(!t.skill.endpoint)throw new Error(`Skill ${t.skill.name} has no endpoint`);let r=new SSEClientTransport(new URL(t.skill.endpoint));await this._mcpClient.connect(r);break}}let{tools:o}=await this._mcpClient.listTools();this._toolDefinitions=o.map(r=>({skillName:t.skill.name,name:r.name,description:r.description,inputSchema:r.inputSchema,interactive:false})),this._initialized=true;}async _initInteractiveSkill(t){this._toolDefinitions=Object.values(t.interactiveSkill.tools).map(o=>({skillName:t.interactiveSkill.name,name:o.name,description:o.description,inputSchema:JSON.parse(o.inputJsonSchema),interactive:true})),this._initialized=true;}async _initDelegate(t){this._toolDefinitions=[{skillName:t.expert.name,name:t.expert.name.split("/").pop()??t.expert.name,description:t.expert.description,inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]},interactive:false}],this._initialized=true;}async close(){this._mcpClient&&await this._mcpClient.close();}async getToolDefinitions(){if(!this._initialized)throw new Error(`${this.name} is not initialized`);if(this._params.type==="mcp"){let t=this._params.skill.omit??[],o=this._params.skill.pick??[];return this._toolDefinitions.filter(r=>t.length>0?!t.includes(r.name):true).filter(r=>o.length>0?o.includes(r.name):true)}return this._toolDefinitions}async callTool(t,o){switch(this._params.type){case "mcp":{if(!this._mcpClient)throw new Error(`${this.name} is not initialized`);try{let r=await this._mcpClient.callTool({name:t,arguments:o});return this._convertToolResult(r,t,o)}catch(r){return this._handleToolError(r,t)}}case "interactive":return [];case "delegate":return []}}_handleToolError(t,o){if(t instanceof McpError)return [{type:"textPart",text:`Error calling tool ${o}: ${t.message}`,id:createId()}];if(t instanceof ZodError)return [{type:"textPart",text:`Invalid tool call arguments: ${t}`,id:createId()}];throw t}_convertToolResult(t,o,r){return !t.content||t.content.length===0?[{type:"textPart",text:`Tool ${o} returned nothing with arguments: ${JSON.stringify(r)}`,id:createId()}]:t.content.filter(a=>a.type!=="audio"&&a.type!=="resource_link").map(a=>this._convertPart(a))}_convertPart(t){switch(t.type){case "text":return !t.text||t.text===""?{type:"textPart",text:"Error: No content",id:createId()}:{type:"textPart",text:t.text,id:createId()};case "image":if(!t.data||!t.mimeType)throw new Error("Image part must have both data and mimeType");return {type:"imageInlinePart",encodedData:t.data,mimeType:t.mimeType,id:createId()};case "resource":if(!t.resource)throw new Error("Resource part must have resource content");return this._convertResource(t.resource)}}_convertResource(t){if(!t.mimeType)throw new Error(`Resource ${JSON.stringify(t)} has no mimeType`);if(t.text&&typeof t.text=="string")return {type:"textPart",text:t.text,id:createId()};if(t.blob&&typeof t.blob=="string")return {type:"fileInlinePart",encodedData:t.blob,mimeType:t.mimeType,id:createId()};throw new Error(`Unsupported resource type: ${JSON.stringify(t)}`)}};async function Ae(e,t){let o={},{skills:r}=e;r["@perstack/base"]||(r["@perstack/base"]={type:"mcpStdioSkill",name:"@perstack/base",description:"The base skill for Perstack",pick:[],omit:[],command:"npx",args:["-y","@perstack/base"],requiredEnv:[]});let a=await Promise.all(Object.values(r).filter(s=>s.type==="mcpStdioSkill"||s.type==="mcpSseSkill").map(async s=>{let u=new z({type:"mcp",skill:s});return await u.init(),u})),c=await Promise.all(Object.values(r).filter(s=>s.type==="interactiveSkill").map(async s=>{let u=new z({type:"interactive",interactiveSkill:s});return await u.init(),u})),m=await Promise.all(e.delegates.map(async s=>{let u=t[s],h=new z({type:"delegate",expert:u});return await h.init(),h}));for(let s of a)o[s.name]=s;for(let s of c)o[s.name]=s;for(let s of m)o[s.name]=s;return o}async function Ge(e){for(let t of Object.values(e))await t.close();}async function N(e,t){for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)if(a.name===t)return o}throw new Error(`Tool ${t} not found`)}async function Ke(e){let t={};for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)t[a.name]={description:a.description,parameters:jsonSchema(a.inputSchema)};}return t}async function qe({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,toolName:c,args:m}=o.toolCall,s=await N(r,c);if(!s||!s.expert)throw new Error(`Delegation error: skill manager "${c}" not found`);if(!m||!m.query||typeof m.query!="string")throw new Error("Delegation error: query is undefined");return $e(e,t,{checkpoint:{...t,status:"stoppedByDelegate",delegateTo:{expert:{key:s.expert.key,name:s.expert.name,version:s.expert.version},toolCallId:a,toolName:c,query:m.query}},step:{...o,finishedAt:new Date().getTime()}})}async function Je({setting:e,checkpoint:t,step:o}){return Ee(e,t,{checkpoint:{...t,status:"stoppedByInteractiveTool"},step:{...o,finishedAt:new Date().getTime()}})}async function Ve({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,skillName:c,toolName:m,args:s}=o.toolCall,u=await N(r,m);if(u.type!=="mcp")throw new Error(`Incorrect SkillType, required MCP, got ${u.type}`);let h=await u.callTool(m,s),d={id:a,skillName:c,toolName:m,result:h};if(c==="@perstack/base"){if(m==="think")return Ce(e,t,{toolResult:d});if(m==="attemptCompletion")return Me(e,t,{toolResult:d});if(m==="readPdfFile")return we(e,t,{toolResult:d});if(m==="readImageFile")return Ie(e,t,{toolResult:d})}return ve(e,t,{toolResult:d})}async function Ye({setting:e,checkpoint:t,step:o}){return e.maxSteps!==void 0&&t.stepNumber>e.maxSteps?Ne(e,t,{checkpoint:{...t,status:"stoppedByExceededMaxSteps"},step:{...o,finishedAt:new Date().getTime()}}):Fe(e,t,{checkpoint:{...t},step:{...o,finishedAt:new Date().getTime()},nextCheckpoint:{...t,id:createId(),stepNumber:t.stepNumber+1}})}function F(e){return {type:"userMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function U(e){return {type:"expertMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function v(e){return {type:"toolMessage",contents:e.map(t=>({...t,contents:t.contents.map(o=>({...o,id:createId()})),id:createId()})),id:createId()}}function W(e){switch(e.type){case "instructionMessage":return {role:"system",content:Wt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "userMessage":return {role:"user",content:Ht(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "expertMessage":return {role:"assistant",content:Qt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "toolMessage":return {role:"tool",content:Zt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0}}}function Wt(e){return e.reduce((t,o)=>dedent`
|
|
1
|
+
import {existsSync}from'fs';import {readFile,writeFile,mkdir,readdir}from'fs/promises';import pe from'path';import {createId}from'@paralleldrive/cuid2';import ko from'smol-toml';import {setup,assign,createActor}from'xstate';import {z as z$1,ZodError}from'zod';import {anthropic}from'@ai-sdk/anthropic';import {google}from'@ai-sdk/google';import {openai}from'@ai-sdk/openai';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {SSEClientTransport}from'@modelcontextprotocol/sdk/client/sse.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {McpError}from'@modelcontextprotocol/sdk/types.js';import {generateText,jsonSchema}from'ai';import {dedent}from'ts-dedent';var ft="claude-4-sonnet-20250514",ge=["claude-4-opus-20250514","claude-4-sonnet-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-latest","claude-3-5-sonnet-20241022","claude-3-5-sonnet-20240620","claude-3-5-haiku-latest","claude-3-5-haiku-20241022"],ue=["gemini-2.5-pro-preview-05-06","gemini-2.5-pro-exp-03-25","gemini-2.5-flash-preview-04-17","gemini-2.0-pro-exp-02-05","gemini-2.0-flash-thinking-exp-01-21","gemini-2.0-flash","gemini-2.0-flash-001","gemini-2.0-flash-live-001","gemini-2.0-flash-lite","gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-pro-latest","gemini-1.5-pro-001","gemini-1.5-pro-002","gemini-1.5-flash","gemini-1.5-flash-latest","gemini-1.5-flash-001","gemini-1.5-flash-002","gemini-1.5-flash-8b","gemini-1.5-flash-8b-latest","gemini-1.5-flash-8b-001"],de=["o4-mini","o4-mini-2025-04-16","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18"],ht=Object.fromEntries([...ge,...ue,...de].map(e=>[e,{default:e===ft,model:e}]));function te(){let e=Object.values(ht).find(t=>t.default);if(!e)throw new Error("No default model found");return e.model}function L(e){let t=e??te();if(ge.includes(t))return anthropic(t);if(ue.includes(t))return google(t);if(de.includes(t))return openai(t);throw new Error(`Unsupported model: ${t}`)}var I=z$1.object({id:z$1.string()}),_=I.extend({type:z$1.literal("textPart"),text:z$1.string()}),yt=I.extend({type:z$1.literal("imageUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),fe=I.extend({type:z$1.literal("imageInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),xt=I.extend({type:z$1.literal("imageBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),kt=I.extend({type:z$1.literal("fileUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),Tt=I.extend({type:z$1.literal("fileInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),Rt=I.extend({type:z$1.literal("fileBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),St=I.extend({type:z$1.literal("toolCallPart"),toolCallId:z$1.string(),toolName:z$1.string(),args:z$1.unknown()}),Pt=I.extend({type:z$1.literal("toolResultPart"),toolCallId:z$1.string(),toolName:z$1.string(),contents:z$1.array(z$1.union([_,fe])),isError:z$1.boolean().optional()}),A=z$1.object({id:z$1.string()}),vt=A.extend({type:z$1.literal("instructionMessage"),contents:z$1.array(_),cache:z$1.boolean().optional()}),Ct=A.extend({type:z$1.literal("userMessage"),contents:z$1.array(z$1.union([_,yt,fe,xt,kt,Tt,Rt])),cache:z$1.boolean().optional()}),wt=A.extend({type:z$1.literal("expertMessage"),contents:z$1.array(z$1.union([_,St])),cache:z$1.boolean().optional()}),It=A.extend({type:z$1.literal("toolMessage"),contents:z$1.array(Pt),cache:z$1.boolean().optional()}),he=z$1.union([vt,Ct,wt,It]);var Mt=/^(@[a-z0-9][a-z0-9_-]*\/)?[a-z0-9][a-z0-9_-]*$/,Et=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/,bt=/^[a-z0-9][a-z0-9_-]*$/,D=/^((?:@[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_\.-]*))?$/,Uo=/^[a-z0-9][a-z0-9._-]*$/,$t=214;function jo(e){let t=e.match(D);if(!t)throw new Error(`Invalid expert key format: ${e}`);let[o,r,a,p]=t;return {key:o,name:r,version:a,tag:p}}var G=z$1.object({type:z$1.literal("mcpStdioSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),command:z$1.string(),packageName:z$1.string().optional(),args:z$1.array(z$1.string()).optional().default([]),requiredEnv:z$1.array(z$1.string()).optional().default([])}),K=z$1.object({type:z$1.literal("mcpSseSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),endpoint:z$1.string()}),ye=z$1.object({name:z$1.string(),description:z$1.string().optional(),inputJsonSchema:z$1.string()}),q=z$1.object({type:z$1.literal("interactiveSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),tools:z$1.record(z$1.string(),ye.omit({name:true})).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,ye.parse({...o,name:t})])))}),J=z$1.object({key:z$1.string().regex(D).min(1),name:z$1.string().regex(Mt).min(1).max($t),version:z$1.string().regex(Et),description:z$1.string().min(1).max(1024*2).optional(),instruction:z$1.string().min(1).max(1024*20),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])).optional().default({"@perstack/base":{type:"mcpStdioSkill",description:"Base skill",command:"npx",args:["-y","@perstack/base"]}}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,z$1.discriminatedUnion("type",[G,K,q]).parse({...o,name:t})]))),delegates:z$1.array(z$1.string().regex(D).min(1)).optional().default([]),tags:z$1.array(z$1.string().regex(bt).min(1)).optional().default([])}),Nt=z$1.object({promptTokens:z$1.number(),completionTokens:z$1.number(),totalTokens:z$1.number(),cacheCreationInputTokens:z$1.number(),cacheReadInputTokens:z$1.number()}),Ft=z$1.enum(["init","proceeding","completed","stoppedByInteractiveTool","stoppedByDelegate","stoppedByExceededMaxSteps","stoppedByError"]),oe=z$1.object({id:z$1.string(),runId:z$1.string(),status:Ft,stepNumber:z$1.number(),messages:z$1.array(he),expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),delegateTo:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),query:z$1.string()}).optional(),delegatedBy:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),checkpointId:z$1.string()}).optional(),usage:Nt}),ke=z$1.object({setting:z$1.object({runId:z$1.string().optional().transform(e=>e??createId()),expertKey:z$1.string().regex(D).min(1),input:z$1.object({text:z$1.string().optional(),interactiveToolCallResult:z$1.object({toolCallId:z$1.string(),toolName:z$1.string(),text:z$1.string()}).optional()}),experts:z$1.record(z$1.string().regex(D).min(1),J.omit({key:true})).optional().default({}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,J.parse({...o,key:t})]))),model:z$1.string().optional().default(te()),temperature:z$1.number().min(0).max(1).optional().default(.3),maxSteps:z$1.number().min(1).optional(),maxRetries:z$1.number().min(0).optional().default(10),workspace:z$1.string().optional(),startedAt:z$1.number().optional().default(Date.now()),updatedAt:z$1.number().optional().default(Date.now())}),checkpoint:oe.optional()});function k(e){return (t,o,r)=>({type:e,id:createId(),expertKey:o.expert.key,timestamp:Date.now(),runId:t.runId,stepNumber:o.stepNumber,...r})}var ne=k("startRun"),Te=k("startGeneration"),re=k("retry"),Re=k("callTool"),Se=k("callInteractiveTool"),Pe=k("callDelegate"),ve=k("resolveToolResult"),Ce=k("resolveThought"),we=k("resolvePdfFile"),Ie=k("resolveImageFile"),Me=k("attemptCompletion"),$=k("finishToolCall"),Ee=k("completeRun"),be=k("stopRunByInteractiveTool"),$e=k("stopRunByDelegate"),Ne=k("stopRunByExceededMaxSteps"),Fe=k("continueToNextStep");async function De(e,t){let o=O(e),a=(await readdir(o,{withFileTypes:true}).then(s=>s.filter(g=>g.isFile()&&g.name.startsWith("checkpoint-")))).find(s=>s.name.endsWith(`-${t}.json`));if(!a)throw new Error(`checkpoint not found: ${e} ${t}`);let p=`${o}/${a.name}`,m=await readFile(p,"utf8");return oe.parse(JSON.parse(m))}async function Oe(e,t){let{id:o,runId:r,stepNumber:a}=e,p=O(r),m=`${p}/checkpoint-${t}-${a}-${o}.json`;await mkdir(p,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}async function Be(e){let{timestamp:t,runId:o,stepNumber:r,type:a}=e,p=O(o),m=`${p}/event-${t}-${r}-${a}.json`;await mkdir(p,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}var ze={version:"0.0.6"};var c=console.info,Le=console.debug,u=e=>{let t=new Date().toISOString(),o=e.stepNumber,r=e.expertKey;return `${t} ${o} ${r}`};async function se(e){switch(await Be(e),e.type){case "startRun":{c(`${u(e)} \u{1F99C} Perstack@${ze.version} started`);let{inputMessages:t}=e;for(let o of t)o.type==="userMessage"?Ot(o):o.type==="toolMessage"&&Bt(o);break}case "startGeneration":{c(`${u(e)} \u{1F99C} Generating tool call`);break}case "retry":{B(e),c(`${u(e)} \u{1F99C} Retrying tool call generation`);break}case "callTool":{if(B(e),c(`${u(e)} \u{1F99C} Calling tool`),e.toolCall.skillName==="@perstack/base")switch(e.toolCall.toolName){case "think":{let t=e.toolCall.args.thought;c(`${u(e)} \u{1F4AD} Thought Updated:`),Le(t);break}case "readPdfFile":{let t=e.toolCall.args.path;c(`${u(e)} \u{1F4C4} Reading PDF: ${t}`);break}case "readImageFile":{let t=e.toolCall.args.path;c(`${u(e)} \u{1F5BC}\uFE0F Reading Image: ${t}`);break}default:{c(`${u(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),c(`${u(e)} \u{1F527} Args: ${e.toolCall.args}`);break}}else c(`${u(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),c(`${u(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callInteractiveTool":{B(e),c(`${u(e)} \u{1F99C} Calling interactive tool`),c(`${u(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),c(`${u(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callDelegate":{B(e),c(`${u(e)} \u{1F99C} Calling delegate`),c(`${u(e)} \u{1F527} Tool: ${e.toolCall.toolName}`),c(`${u(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "resolveToolResult":{if(c(`${u(e)} \u{1F527} Resolved Tool Result`),e.toolResult.skillName==="@perstack/base")switch(e.toolResult.toolName){case "todo":{let t=e.toolResult.result.find(r=>r.type==="textPart")?.text,{todos:o}=JSON.parse(t??"{}");c(`${u(e)} \u{1F4C4} Todo:`);for(let r of o)Le(`${r.completed?"[x]":"[ ]"} ${r.id}: ${r.title}`);break}default:{c(`${u(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),c(`${u(e)} \u{1F527} Result: ${e.toolResult.result}`);break}}else c(`${u(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),c(`${u(e)} \u{1F527} Result: ${e.toolResult.result}`);break}case "resolveThought":{c(`${u(e)} \u{1F4AD} Resolved Thought:`,e.toolResult);break}case "resolvePdfFile":{c(`${u(e)} \u{1F4C4} Resolved PDF:`,e.toolResult);break}case "resolveImageFile":{c(`${u(e)} \u{1F5BC}\uFE0F Resolved Image:`,e.toolResult);break}case "attemptCompletion":{c(`${u(e)} \u2705 Attempting completion`);break}case "completeRun":{B(e),c(`${u(e)} \u{1F99C} Completing run`),c(`${u(e)} \u{1F99C} Result:`,e.text);break}case "stopRunByInteractiveTool":{c(`${u(e)} \u{1F99C} Stopping run by interactive tool`);break}case "stopRunByDelegate":{c(`${u(e)} \u{1F99C} Stopping run by delegate`);break}case "stopRunByExceededMaxSteps":{c(`${u(e)} \u{1F99C} Stopping run by exceeded max steps`);break}case "continueToNextStep":{c(`${u(e)} \u{1F99C} Continuing to next step`);break}}}function Ot(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)r.type==="textPart"?c(`${t} \u{1F4AC} User: ${r.text}`):r.type==="imageUrlPart"?c(`${t} \u{1F5BC}\uFE0F User: ${r.url}`):r.type==="imageInlinePart"?c(`${t} \u{1F5BC}\uFE0F User: Inline image`):r.type==="imageBinaryPart"?c(`${t} \u{1F5BC}\uFE0F User: Binary image`):r.type==="fileUrlPart"?c(`${t} \u{1F4C4} User: ${r.url}`):r.type==="fileInlinePart"?c(`${t} \u{1F4C4} User: Inline file`):r.type==="fileBinaryPart"&&c(`${t} \u{1F4C4} User: Binary file`);}function Bt(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)if(r.type==="toolResultPart"){let{contents:a}=r;for(let p of a)p.type==="textPart"?c(`${t} \u{1F4AC} Tool Result: ${p.text}`):p.type==="imageInlinePart"&&c(`${t} \u{1F5BC}\uFE0F Tool Result: Inline image`);}}function B(e){let t=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");c(`${u(e)} \u{1F4CA} Tokens usage: ${t}`);let o=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");c(`${u(e)} \u{1F4CA} Total usage: ${o}`);}var V=class{listeners=[];subscribe(t){this.listeners.push(t);}async emit(t){for(let o of this.listeners)await o({...t,id:createId(),timestamp:Date.now()});}};var Lt=z$1.object({name:z$1.string(),version:z$1.string(),minRuntimeVersion:z$1.string(),description:z$1.string(),instruction:z$1.string(),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])),delegates:z$1.array(z$1.string()),tags:z$1.array(z$1.string()),status:z$1.string(),owner:z$1.object({name:z$1.string()}),createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()}),_e=z$1.object({data:z$1.object({expert:Lt})});var Y=class{baseUrl;registry;apiKey;constructor(t){this.baseUrl=t?.baseUrl??process.env.PERSTACK_API_BASE_URL??"https://api.perstack.ai",this.apiKey=t?.apiKey??process.env.PERSTACK_API_KEY,this.registry=new ae(this);}},ae=class{client;endpoint;constructor(t){this.client=t,this.endpoint="/api/registry/v1/experts";}async get(t){let o=encodeURIComponent(t),r=new URL(`${this.endpoint}/${o}`,this.client.baseUrl),a={"Content-Type":"application/json",Authorization:`Bearer ${this.client.apiKey}`},p=await fetch(r.toString(),{headers:a});if(!p.ok)throw new Error(`Registry returned non-200 status code: ${p.status}, reason: ${p.statusText}`);let m=await p.json();return _e.parse(m)}};async function ie(e,t){if(t[e])return t[e];let o=new Y,{data:r}=await o.registry.get(e),a=J.parse({...r.expert,key:e});return t[e]=a,a}var z=class{_toolDefinitions=[];_initialized=false;name;type;skill;interactiveSkill;expert;_mcpClient;_params;constructor(t){switch(this._params=t,this.type=t.type,t.type){case "mcp":this.name=t.skill.name,this.skill=t.skill;break;case "interactive":this.name=t.interactiveSkill.name,this.interactiveSkill=t.interactiveSkill;break;case "delegate":this.name=t.expert.name,this.expert=t.expert;break}}async init(){switch(this._params.type){case "mcp":{await this._initMcpSkill(this._params);break}case "interactive":{await this._initInteractiveSkill(this._params);break}case "delegate":{await this._initDelegate(this._params);break}}}async _initMcpSkill(t){switch(this._mcpClient=new Client({name:`${t.skill.name}-mcp-client`,version:"1.0.0"}),t.skill.type){case "mcpStdioSkill":{if(!t.skill.command)throw new Error(`Skill ${t.skill.name} has no command`);let{command:r,packageName:a,args:p,requiredEnv:m}=t.skill;if(!a&&(!p||p.length===0))throw new Error(`Skill ${t.skill.name} has no packageName or args. Please provide one of them.`);if(a&&p&&p.length>0)throw new Error(`Skill ${t.skill.name} has both packageName and args. Please provide only one of them.`);let s=new StdioClientTransport({command:r,args:p??[a],env:Object.fromEntries(Object.entries(process.env).filter(([g,f])=>f!==void 0&&f!=="").map(([g,f])=>[g,f]))});await this._mcpClient.connect(s);break}case "mcpSseSkill":{if(!t.skill.endpoint)throw new Error(`Skill ${t.skill.name} has no endpoint`);let r=new SSEClientTransport(new URL(t.skill.endpoint));await this._mcpClient.connect(r);break}}let{tools:o}=await this._mcpClient.listTools();this._toolDefinitions=o.map(r=>({skillName:t.skill.name,name:r.name,description:r.description,inputSchema:r.inputSchema,interactive:false})),this._initialized=true;}async _initInteractiveSkill(t){this._toolDefinitions=Object.values(t.interactiveSkill.tools).map(o=>({skillName:t.interactiveSkill.name,name:o.name,description:o.description,inputSchema:JSON.parse(o.inputJsonSchema),interactive:true})),this._initialized=true;}async _initDelegate(t){this._toolDefinitions=[{skillName:t.expert.name,name:t.expert.name.split("/").pop()??t.expert.name,description:t.expert.description,inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]},interactive:false}],this._initialized=true;}async close(){this._mcpClient&&await this._mcpClient.close();}async getToolDefinitions(){if(!this._initialized)throw new Error(`${this.name} is not initialized`);if(this._params.type==="mcp"){let t=this._params.skill.omit??[],o=this._params.skill.pick??[];return this._toolDefinitions.filter(r=>t.length>0?!t.includes(r.name):true).filter(r=>o.length>0?o.includes(r.name):true)}return this._toolDefinitions}async callTool(t,o){switch(this._params.type){case "mcp":{if(!this._mcpClient)throw new Error(`${this.name} is not initialized`);try{let r=await this._mcpClient.callTool({name:t,arguments:o});return this._convertToolResult(r,t,o)}catch(r){return this._handleToolError(r,t)}}case "interactive":return [];case "delegate":return []}}_handleToolError(t,o){if(t instanceof McpError)return [{type:"textPart",text:`Error calling tool ${o}: ${t.message}`,id:createId()}];if(t instanceof ZodError)return [{type:"textPart",text:`Invalid tool call arguments: ${t}`,id:createId()}];throw t}_convertToolResult(t,o,r){return !t.content||t.content.length===0?[{type:"textPart",text:`Tool ${o} returned nothing with arguments: ${JSON.stringify(r)}`,id:createId()}]:t.content.filter(a=>a.type!=="audio"&&a.type!=="resource_link").map(a=>this._convertPart(a))}_convertPart(t){switch(t.type){case "text":return !t.text||t.text===""?{type:"textPart",text:"Error: No content",id:createId()}:{type:"textPart",text:t.text,id:createId()};case "image":if(!t.data||!t.mimeType)throw new Error("Image part must have both data and mimeType");return {type:"imageInlinePart",encodedData:t.data,mimeType:t.mimeType,id:createId()};case "resource":if(!t.resource)throw new Error("Resource part must have resource content");return this._convertResource(t.resource)}}_convertResource(t){if(!t.mimeType)throw new Error(`Resource ${JSON.stringify(t)} has no mimeType`);if(t.text&&typeof t.text=="string")return {type:"textPart",text:t.text,id:createId()};if(t.blob&&typeof t.blob=="string")return {type:"fileInlinePart",encodedData:t.blob,mimeType:t.mimeType,id:createId()};throw new Error(`Unsupported resource type: ${JSON.stringify(t)}`)}};async function Ae(e,t){let o={},{skills:r}=e;r["@perstack/base"]||(r["@perstack/base"]={type:"mcpStdioSkill",name:"@perstack/base",description:"The base skill for Perstack",pick:[],omit:[],command:"npx",args:["-y","@perstack/base"],requiredEnv:[]});let a=await Promise.all(Object.values(r).filter(s=>s.type==="mcpStdioSkill"||s.type==="mcpSseSkill").map(async s=>{let g=new z({type:"mcp",skill:s});return await g.init(),g})),p=await Promise.all(Object.values(r).filter(s=>s.type==="interactiveSkill").map(async s=>{let g=new z({type:"interactive",interactiveSkill:s});return await g.init(),g})),m=await Promise.all(e.delegates.map(async s=>{let g=t[s],f=new z({type:"delegate",expert:g});return await f.init(),f}));for(let s of a)o[s.name]=s;for(let s of p)o[s.name]=s;for(let s of m)o[s.name]=s;return o}async function Ge(e){for(let t of Object.values(e))await t.close();}async function N(e,t){for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)if(a.name===t)return o}throw new Error(`Tool ${t} not found`)}async function Ke(e){let t={};for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)t[a.name]={description:a.description,parameters:jsonSchema(a.inputSchema)};}return t}async function qe({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,toolName:p,args:m}=o.toolCall,s=await N(r,p);if(!s||!s.expert)throw new Error(`Delegation error: skill manager "${p}" not found`);if(!m||!m.query||typeof m.query!="string")throw new Error("Delegation error: query is undefined");return $e(e,t,{checkpoint:{...t,status:"stoppedByDelegate",delegateTo:{expert:{key:s.expert.key,name:s.expert.name,version:s.expert.version},toolCallId:a,toolName:p,query:m.query}},step:{...o,finishedAt:new Date().getTime()}})}async function Je({setting:e,checkpoint:t,step:o}){return be(e,t,{checkpoint:{...t,status:"stoppedByInteractiveTool"},step:{...o,finishedAt:new Date().getTime()}})}async function Ve({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,skillName:p,toolName:m,args:s}=o.toolCall,g=await N(r,m);if(g.type!=="mcp")throw new Error(`Incorrect SkillType, required MCP, got ${g.type}`);let f=await g.callTool(m,s),d={id:a,skillName:p,toolName:m,result:f};if(p==="@perstack/base"){if(m==="think")return Ce(e,t,{toolResult:d});if(m==="attemptCompletion")return Me(e,t,{toolResult:d});if(m==="readPdfFile")return we(e,t,{toolResult:d});if(m==="readImageFile")return Ie(e,t,{toolResult:d})}return ve(e,t,{toolResult:d})}async function Ye({setting:e,checkpoint:t,step:o}){return e.maxSteps!==void 0&&t.stepNumber>e.maxSteps?Ne(e,t,{checkpoint:{...t,status:"stoppedByExceededMaxSteps"},step:{...o,finishedAt:new Date().getTime()}}):Fe(e,t,{checkpoint:{...t},step:{...o,finishedAt:new Date().getTime()},nextCheckpoint:{...t,id:createId(),stepNumber:t.stepNumber+1}})}function F(e){return {type:"userMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function U(e){return {type:"expertMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function v(e){return {type:"toolMessage",contents:e.map(t=>({...t,contents:t.contents.map(o=>({...o,id:createId()})),id:createId()})),id:createId()}}function W(e){switch(e.type){case "instructionMessage":return {role:"system",content:Wt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "userMessage":return {role:"user",content:Ht(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "expertMessage":return {role:"assistant",content:Qt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "toolMessage":return {role:"tool",content:Zt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0}}}function Wt(e){return e.reduce((t,o)=>dedent`
|
|
2
2
|
${t}
|
|
3
3
|
${o.text}
|
|
4
|
-
`.trim(),"")}function Ht(e){return e.map(t=>{switch(t.type){case "textPart":return We(t);case "imageUrlPart":return Xt(t);case "imageInlinePart":return eo(t);case "imageBinaryPart":return to(t);case "fileUrlPart":return oo(t);case "fileInlinePart":return no(t);case "fileBinaryPart":return ro(t)}})}function Qt(e){return e.map(t=>{switch(t.type){case "textPart":return We(t);case "toolCallPart":return so(t)}})}function Zt(e){return e.map(t=>{switch(t.type){case "toolResultPart":return ao(t)}})}function We(e){return {type:"text",text:e.text}}function Xt(e){return {type:"image",image:e.url,mimeType:e.mimeType}}function eo(e){return {type:"image",image:e.encodedData,mimeType:e.mimeType}}function to(e){return {type:"image",image:e.data,mimeType:e.mimeType}}function oo(e){return {type:"file",data:e.url,mimeType:e.mimeType}}function no(e){return {type:"file",data:e.encodedData,mimeType:e.mimeType}}function ro(e){return {type:"file",data:e.data,mimeType:e.mimeType}}function so(e){return {type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}function ao(e){return {type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,result:e.contents,experimental_content:e.contents.map(t=>{switch(t.type){case "textPart":return {type:"text",text:t.text};case "imageInlinePart":return {type:"image",data:t.encodedData,mimeType:t.mimeType}}}),isError:e.isError}}function H(){return {promptTokens:0,completionTokens:0,totalTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0}}function Q(e){let t=0,o=0;if(e.providerMetadata?.anthropic){let r=e.providerMetadata.anthropic;t=r.cacheCreationInputTokens||0,o=r.cacheReadInputTokens||0;}return {promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,totalTokens:e.usage.totalTokens,cacheCreationInputTokens:t,cacheReadInputTokens:o}}function C(e,t){return {promptTokens:e.promptTokens+t.promptTokens,completionTokens:e.completionTokens+t.completionTokens,totalTokens:e.totalTokens+t.totalTokens,cacheCreationInputTokens:e.cacheCreationInputTokens+t.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens+t.cacheReadInputTokens}}async function He({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:
|
|
4
|
+
`.trim(),"")}function Ht(e){return e.map(t=>{switch(t.type){case "textPart":return We(t);case "imageUrlPart":return Xt(t);case "imageInlinePart":return eo(t);case "imageBinaryPart":return to(t);case "fileUrlPart":return oo(t);case "fileInlinePart":return no(t);case "fileBinaryPart":return ro(t)}})}function Qt(e){return e.map(t=>{switch(t.type){case "textPart":return We(t);case "toolCallPart":return so(t)}})}function Zt(e){return e.map(t=>{switch(t.type){case "toolResultPart":return ao(t)}})}function We(e){return {type:"text",text:e.text}}function Xt(e){return {type:"image",image:e.url,mimeType:e.mimeType}}function eo(e){return {type:"image",image:e.encodedData,mimeType:e.mimeType}}function to(e){return {type:"image",image:e.data,mimeType:e.mimeType}}function oo(e){return {type:"file",data:e.url,mimeType:e.mimeType}}function no(e){return {type:"file",data:e.encodedData,mimeType:e.mimeType}}function ro(e){return {type:"file",data:e.data,mimeType:e.mimeType}}function so(e){return {type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}function ao(e){return {type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,result:e.contents,experimental_content:e.contents.map(t=>{switch(t.type){case "textPart":return {type:"text",text:t.text};case "imageInlinePart":return {type:"image",data:t.encodedData,mimeType:t.mimeType}}}),isError:e.isError}}function H(){return {promptTokens:0,completionTokens:0,totalTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0}}function Q(e){let t=0,o=0;if(e.providerMetadata?.anthropic){let r=e.providerMetadata.anthropic;t=r.cacheCreationInputTokens||0,o=r.cacheReadInputTokens||0;}return {promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,totalTokens:e.usage.totalTokens,cacheCreationInputTokens:t,cacheReadInputTokens:o}}function C(e,t){return {promptTokens:e.promptTokens+t.promptTokens,completionTokens:e.completionTokens+t.completionTokens,totalTokens:e.totalTokens+t.totalTokens,cacheCreationInputTokens:e.cacheCreationInputTokens+t.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens+t.cacheReadInputTokens}}async function He({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:p}=o.toolResult,m=v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:p.filter(h=>h.type==="textPart"||h.type==="imageInlinePart")}]),s=L(e.model),{messages:g}=t,f=await generateText({model:s,messages:[...g,m].map(W),temperature:e.temperature,maxRetries:e.maxRetries}),d=Q(f),{text:P}=f,R=[m,U(P?[{type:"textPart",text:P}]:[])];return Ee(e,t,{checkpoint:{...t,messages:[...g,...R],usage:C(t.usage,d),status:"completed"},step:{...o,newMessages:[...o.newMessages,...R],finishedAt:new Date().getTime(),usage:C(o.usage,d)},text:P,usage:d})}async function Qe({setting:e,checkpoint:t,skillManagers:o}){let{messages:r}=t,a=L(e.model),p=await generateText({model:a,messages:r.map(W),temperature:e.temperature,maxRetries:e.maxRetries,tools:await Ke(o),toolChoice:"required"}),m=Q(p),{text:s,toolCalls:g,finishReason:f}=p,d=g[0];if(!d)return re(e,t,{newMessages:[U(s?[{type:"textPart",text:s}]:[]),F([{type:"textPart",text:"You must generate a tool call. Try again."}])],usage:m});if(f!=="tool-calls")switch(f){case "length":return re(e,t,{newMessages:[U([{type:"toolCallPart",toolCallId:d.toolCallId,toolName:d.toolName,args:d.args}]),v([{type:"toolResultPart",toolCallId:d.toolCallId,toolName:d.toolName,contents:[{type:"textPart",text:"Error: Generation length exceeded"}]}])],usage:m});default:throw new Error(`Unexpected finish reason: ${f}`)}let P=[{type:"toolCallPart",toolCallId:d.toolCallId,toolName:d.toolName,args:d.args}];s&&P.push({type:"textPart",text:s});let R=await N(o,d.toolName),h={newMessage:U(P),toolCall:{id:d.toolCallId,skillName:R.name,toolName:d.toolName,args:d.args},usage:m};switch(R.type){case "mcp":return Re(e,t,h);case "interactive":return Se(e,t,h);case "delegate":return Pe(e,t,h)}}var po=dedent`
|
|
5
5
|
IMPORTANT:
|
|
6
6
|
You are NOT an "interactive" AI agent.
|
|
7
7
|
From the start of the agent loop until the completion of the task,
|
|
@@ -76,5 +76,5 @@ import {existsSync}from'fs';import {readFile,writeFile,mkdir,readdir}from'fs/pro
|
|
|
76
76
|
|
|
77
77
|
About "${a.name}":
|
|
78
78
|
${a.description}
|
|
79
|
-
`.trim():o},"")}async function tt({setting:e,checkpoint:t}){let{expertKey:o,experts:r}=e,a=r[o];switch(t.status){case "init":return ne(e,t,{initialCheckpoint:t,inputMessages:[Xe(a,r),et(e.input)]});default:return ne(e,t,{initialCheckpoint:t,inputMessages:[et(e.input)]})}}function et(e){if(e.text)return F([{type:"textPart",text:e.text}]);if(e.interactiveToolCallResult)return v([{type:"toolResultPart",toolCallId:e.interactiveToolCallResult.toolCallId,toolName:e.interactiveToolCallResult.toolName,contents:[{type:"textPart",text:e.interactiveToolCallResult.text}]}]);throw new Error("Input message is undefined")}async function ot({setting:e,checkpoint:t}){return ke(e,t,{messages:t.messages})}async function nt({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:c}=o.toolResult,m=c.filter(u=>u.type==="textPart"),s=[];for(let u of m){let h;try{h=JSON.parse(u.text);}catch{s.push({type:"textPart",text:u.text});continue}let{path:d,mimeType:P,size:R}=h,f=await readFile(d).then(S=>({encodedData:S.toString("base64"),mimeType:P,size:R}));s.push({type:"imageInlinePart",encodedData:f.encodedData,mimeType:f.mimeType});}return $(e,t,{newMessages:[v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:s}])]})}async function rt({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:c}=o.toolResult,m=c.filter(u=>u.type==="textPart"),s=[];for(let u of m){let h;try{h=JSON.parse(u.text);}catch{s.push({type:"textPart",text:u.text});continue}let{path:d,mimeType:P,size:R}=h,f=await readFile(d).then(S=>({encodedData:S.toString("base64"),mimeType:P,size:R}));s.push({type:"fileInlinePart",encodedData:f.encodedData,mimeType:f.mimeType});}return $(e,t,{newMessages:[v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:[{type:"textPart",text:"User uploads PDF file as follows."}]}]),F(s)]})}async function X({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:c}=o.toolResult;return $(e,t,{newMessages:[v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:c.filter(m=>m.type==="textPart"||m.type==="imageInlinePart")}])]})}async function st(e){return X(e)}var at=setup({types:{input:{},context:{},events:{}}}).createMachine({id:"Run",initial:"Init",context:({input:e})=>({setting:e.setting,checkpoint:e.initialCheckpoint,eventListener:e.eventListener,skillManagers:e.skillManagers}),states:{Init:{on:{startRun:{target:"PreparingForStep",actions:assign({checkpoint:({event:e})=>({...e.initialCheckpoint,messages:[...e.initialCheckpoint.messages,...e.inputMessages],status:"proceeding"})})}}},PreparingForStep:{on:{startGeneration:{target:"GeneratingToolCall",actions:assign({step:({context:e,event:t})=>({stepNumber:e.checkpoint.stepNumber,newMessages:[],usage:H(),startedAt:t.timestamp})})}}},GeneratingToolCall:{on:{retry:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:t.newMessages,usage:C(e.step.usage,t.usage)})})},callTool:{target:"CallingTool",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,t.newMessage],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:[t.newMessage],toolCall:t.toolCall,usage:C(e.step.usage,t.usage)})})},callInteractiveTool:{target:"CallingInteractiveTool",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,t.newMessage],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:[t.newMessage],toolCall:t.toolCall,usage:C(e.step.usage,t.usage)})})},callDelegate:{target:"CallingDelegate",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,t.newMessage],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:[t.newMessage],toolCall:t.toolCall,usage:C(e.step.usage,t.usage)})})}}},CallingTool:{on:{resolveToolResult:{target:"ResolvingToolResult",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},resolveThought:{target:"ResolvingThought",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},resolvePdfFile:{target:"ResolvingPdfFile",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},resolveImageFile:{target:"ResolvingImageFile",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},attemptCompletion:{target:"GeneratingRunResult",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})}}},ResolvingToolResult:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},ResolvingThought:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},ResolvingPdfFile:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},ResolvingImageFile:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},GeneratingRunResult:{on:{completeRun:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},CallingInteractiveTool:{on:{stopRunByInteractiveTool:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},CallingDelegate:{on:{stopRunByDelegate:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},FinishingStep:{on:{continueToNextStep:{target:"PreparingForStep",actions:assign({checkpoint:({event:e})=>e.nextCheckpoint,step:({event:e})=>e.step}),reenter:true},stopRunByExceededMaxSteps:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},Stopped:{type:"final"}}}),it={Init:tt,PreparingForStep:ot,GeneratingToolCall:Qe,CallingTool:Ve,ResolvingToolResult:X,ResolvingThought:st,ResolvingPdfFile:rt,ResolvingImageFile:nt,GeneratingRunResult:He,CallingInteractiveTool:Je,CallingDelegate:qe,FinishingStep:Ye};var lt=z$1.object({model:z$1.string().optional(),temperature:z$1.number().optional(),maxSteps:z$1.number().optional(),maxRetries:z$1.number().optional(),experts:z$1.record(z$1.string(),z$1.object({version:z$1.string().optional(),minRuntimeVersion:z$1.string().optional(),description:z$1.string().optional(),instruction:z$1.string(),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[z$1.object({type:z$1.literal("mcpStdioSkill"),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional(),omit:z$1.array(z$1.string()).optional(),command:z$1.string(),args:z$1.array(z$1.string()).optional(),requiredEnv:z$1.array(z$1.string()).optional()}),z$1.object({type:z$1.literal("mcpSseSkill"),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional(),omit:z$1.array(z$1.string()).optional(),endpoint:z$1.string()}),z$1.object({type:z$1.literal("interactiveSkill"),description:z$1.string().optional(),rule:z$1.string().optional(),tools:z$1.record(z$1.string(),z$1.object({description:z$1.string().optional(),inputJsonSchema:z$1.string()}))})])).optional(),delegates:z$1.array(z$1.string()).optional()})).optional()});async function Br(e,t){let o=Te.parse(e),r=t?.eventListener??se,a=t?.retrieveCheckpoint??De,c=t?.storeCheckpoint??Oe,m=new V;m.subscribe(r);let{setting:s,checkpoint:u}=o;if(s.workspace){if(!pe.isAbsolute(s.workspace))throw new Error(`Workspace path must be absolute: ${s.workspace}`);process.chdir(s.workspace);}for(await Po(s);;){let{expertToRun:h,experts:d}=await Ro(s);So(h.name,d,s),console.log("experts",d);let P=await Ae(h,d),R=createActor(at,{input:{setting:{...s,experts:d},initialCheckpoint:u??{id:createId(),runId:s.runId,expert:{key:s.expertKey,name:h.name,version:h.version},stepNumber:1,status:"init",messages:[],usage:H()},eventListener:r,skillManagers:P}}),f=await new Promise((S,j)=>{R.subscribe(async M=>{try{if(M.value==="Stopped"){let{checkpoint:k,skillManagers:ee}=M.context;if(!k)throw new Error("Checkpoint is undefined");await Ge(ee),S(k);}else {let k=await it[M.value](M.context);"checkpoint"in k&&await c(k.checkpoint,k.timestamp),await m.emit(k),R.send(k);}}catch(k){j(k);}}),R.start();});switch(f.status){case "completed":{if(f.delegatedBy){let{messages:S,delegatedBy:j}=f,{expert:M,toolCallId:k,toolName:ee,checkpointId:ct}=j,ce=S[S.length-1];if(ce.type!=="expertMessage")throw new Error("Delegation error: delegation result message is incorrect");let me=ce.contents.find(mt=>mt.type==="textPart");if(!me)throw new Error("Delegation error: delegation result message does not contain a text");s={...s,expertKey:M.key,input:{interactiveToolCallResult:{toolCallId:k,toolName:ee,text:me.text}}},u={...await a(s.runId,ct),id:createId(),stepNumber:f.stepNumber+1,usage:f.usage};break}return f}case "stoppedByInteractiveTool":return f;case "stoppedByDelegate":{if(!f.delegateTo)throw new Error("Delegation error: delegate to is undefined");let{expert:S,toolCallId:j,toolName:M,query:k}=f.delegateTo;s={...s,expertKey:S.key,input:{text:k}},u={id:createId(),runId:s.runId,status:"init",stepNumber:f.stepNumber+1,messages:[],expert:{key:S.key,name:S.name,version:S.version},delegatedBy:{expert:{key:h.key,name:h.name,version:h.version},toolCallId:j,toolName:M,checkpointId:f.id},usage:f.usage};break}case "stoppedByExceededMaxSteps":return f;case "stoppedByError":return f;default:throw new Error("Run stopped by unknown reason")}}}async function Ro(e){let{expertKey:t}=e,o={...e.experts},r=await ie(t,o);for(let a of r.delegates)if(!await ie(a,o))throw new Error(`Delegate ${a} not found`);return {expertToRun:r,experts:o}}function So(e,t,o){console.log("\u{1F99C} Starting Perstack \u{1F99C}"),console.log(`Expert To Run: ${e}`),console.log(`Experts: ${Object.keys(t).join(", ")}`),console.log(`Model: ${o.model}`),console.log(`Temperature: ${o.temperature}`),console.log(`Max Steps: ${o.maxSteps}`),console.log(`Max Retries: ${o.maxRetries}`),o.input.text&&console.log(`Query: ${o.input.text}`),o.input.interactiveToolCallResult&&(console.log(`Tool: ${o.input.interactiveToolCallResult.toolName}`),console.log(`Tool Call ID: ${o.input.interactiveToolCallResult.toolCallId}`),console.log(`Tool Result: ${o.input.interactiveToolCallResult.text}`));}async function Po(e){let t=O(e.runId);if(existsSync(t)){let o=pe.resolve(t,"run-setting.json"),r=JSON.parse(await readFile(o,"utf-8"));r.updatedAt=Date.now(),await writeFile(o,JSON.stringify(r,null,2),"utf-8");}else await mkdir(t,{recursive:true}),await writeFile(pe.resolve(t,"run-setting.json"),JSON.stringify(e,null,2),"utf-8");}function O(e){return `${process.cwd()}/perstack/runs/${e}`}async function zr(e){let t=To.parse(e??"");return lt.parse(t)}var Ar=z$1.object({expertKey:z$1.string(),query:z$1.string(),options:z$1.object({config:z$1.string().optional(),model:z$1.string().optional(),temperature:z$1.string().optional().transform(e=>{if(e===void 0)return;let t=Number.parseFloat(e);if(!Number.isNaN(t))return t}),maxSteps:z$1.string().optional().transform(e=>{if(e===void 0)return;let t=Number.parseInt(e);if(!Number.isNaN(t))return t}),maxRetries:z$1.string().optional().transform(e=>{if(e===void 0)return;let t=Number.parseInt(e);if(!Number.isNaN(t))return t}),runId:z$1.string().optional()})});export{oe as CheckpointSchema,Ft as CheckpointStatusSchema,wt as ExpertMessageSchema,J as ExpertSchema,Rt as FileBinaryPartSchema,kt as FileInlinePartSchema,Tt as FileUrlPartSchema,xt as ImageBinaryPartSchema,fe as ImageInlinePartSchema,yt as ImageUrlPartSchema,vt as InstructionMessageSchema,q as InteractiveSkillSchema,ye as InteractiveToolSchema,K as McpSseSkillSchema,G as McpStdioSkillSchema,he as MessageSchema,lt as PerstackConfigSchema,_e as RegistryV1ExpertsGetResponseSchema,Ar as RunInputSchema,Te as RunParamsSchema,it as StateMachineLogics,_ as TextPartSchema,St as ToolCallPartSchema,It as ToolMessageSchema,Pt as ToolResultPartSchema,Nt as UsageSchema,Ct as UserMessageSchema,Me as attemptCompletion,Pe as callDelegate,Se as callInteractiveTool,Re as callTool,be as completeRun,Fe as continueToNextStep,T as createEvent,se as defaultEventListener,D as expertKeyRegex,Mt as expertNameRegex,$ as finishToolCall,O as getRunDir,$t as maxNameLength,zr as parseConfig,jo as parseExpertKey,Ie as resolveImageFile,we as resolvePdfFile,Ce as resolveThought,ve as resolveToolResult,re as retry,Br as run,at as runtimeStateMachine,Uo as skillNameRegex,ke as startGeneration,ne as startRun,$e as stopRunByDelegate,Ne as stopRunByExceededMaxSteps,Ee as stopRunByInteractiveTool,Et as tagNameRegex,bt as versionRegex};//# sourceMappingURL=index.js.map
|
|
79
|
+
`.trim():o},"")}async function tt({setting:e,checkpoint:t}){let{expertKey:o,experts:r}=e,a=r[o];switch(t.status){case "init":return ne(e,t,{initialCheckpoint:t,inputMessages:[Xe(a,r),et(e.input)]});default:return ne(e,t,{initialCheckpoint:t,inputMessages:[et(e.input)]})}}function et(e){if(e.text)return F([{type:"textPart",text:e.text}]);if(e.interactiveToolCallResult)return v([{type:"toolResultPart",toolCallId:e.interactiveToolCallResult.toolCallId,toolName:e.interactiveToolCallResult.toolName,contents:[{type:"textPart",text:e.interactiveToolCallResult.text}]}]);throw new Error("Input message is undefined")}async function ot({setting:e,checkpoint:t}){return Te(e,t,{messages:t.messages})}async function nt({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:p}=o.toolResult,m=p.filter(g=>g.type==="textPart"),s=[];for(let g of m){let f;try{f=JSON.parse(g.text);}catch{s.push({type:"textPart",text:g.text});continue}let{path:d,mimeType:P,size:R}=f,h=await readFile(d).then(S=>({encodedData:S.toString("base64"),mimeType:P,size:R}));s.push({type:"imageInlinePart",encodedData:h.encodedData,mimeType:h.mimeType});}return $(e,t,{newMessages:[v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:s}])]})}async function rt({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:p}=o.toolResult,m=p.filter(g=>g.type==="textPart"),s=[];for(let g of m){let f;try{f=JSON.parse(g.text);}catch{s.push({type:"textPart",text:g.text});continue}let{path:d,mimeType:P,size:R}=f,h=await readFile(d).then(S=>({encodedData:S.toString("base64"),mimeType:P,size:R}));s.push({type:"fileInlinePart",encodedData:h.encodedData,mimeType:h.mimeType});}return $(e,t,{newMessages:[v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:[{type:"textPart",text:"User uploads PDF file as follows."}]}]),F(s)]})}async function X({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:p}=o.toolResult;return $(e,t,{newMessages:[v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:p.filter(m=>m.type==="textPart"||m.type==="imageInlinePart")}])]})}async function st(e){return X(e)}var at=setup({types:{input:{},context:{},events:{}}}).createMachine({id:"Run",initial:"Init",context:({input:e})=>({setting:e.setting,checkpoint:e.initialCheckpoint,eventListener:e.eventListener,skillManagers:e.skillManagers}),states:{Init:{on:{startRun:{target:"PreparingForStep",actions:assign({checkpoint:({event:e})=>({...e.initialCheckpoint,messages:[...e.initialCheckpoint.messages,...e.inputMessages],status:"proceeding"})})}}},PreparingForStep:{on:{startGeneration:{target:"GeneratingToolCall",actions:assign({step:({context:e,event:t})=>({stepNumber:e.checkpoint.stepNumber,newMessages:[],usage:H(),startedAt:t.timestamp})})}}},GeneratingToolCall:{on:{retry:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:t.newMessages,usage:C(e.step.usage,t.usage)})})},callTool:{target:"CallingTool",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,t.newMessage],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:[t.newMessage],toolCall:t.toolCall,usage:C(e.step.usage,t.usage)})})},callInteractiveTool:{target:"CallingInteractiveTool",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,t.newMessage],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:[t.newMessage],toolCall:t.toolCall,usage:C(e.step.usage,t.usage)})})},callDelegate:{target:"CallingDelegate",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,t.newMessage],usage:C(e.checkpoint.usage,t.usage)}),step:({context:e,event:t})=>({...e.step,newMessages:[t.newMessage],toolCall:t.toolCall,usage:C(e.step.usage,t.usage)})})}}},CallingTool:{on:{resolveToolResult:{target:"ResolvingToolResult",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},resolveThought:{target:"ResolvingThought",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},resolvePdfFile:{target:"ResolvingPdfFile",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},resolveImageFile:{target:"ResolvingImageFile",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})},attemptCompletion:{target:"GeneratingRunResult",actions:assign({step:({context:e,event:t})=>({...e.step,toolResult:t.toolResult})})}}},ResolvingToolResult:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},ResolvingThought:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},ResolvingPdfFile:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},ResolvingImageFile:{on:{finishToolCall:{target:"FinishingStep",actions:assign({checkpoint:({context:e,event:t})=>({...e.checkpoint,messages:[...e.checkpoint.messages,...t.newMessages]}),step:({context:e,event:t})=>({...e.step,newMessages:[...e.step.newMessages,...t.newMessages]})})}}},GeneratingRunResult:{on:{completeRun:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},CallingInteractiveTool:{on:{stopRunByInteractiveTool:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},CallingDelegate:{on:{stopRunByDelegate:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},FinishingStep:{on:{continueToNextStep:{target:"PreparingForStep",actions:assign({checkpoint:({event:e})=>e.nextCheckpoint,step:({event:e})=>e.step}),reenter:true},stopRunByExceededMaxSteps:{target:"Stopped",actions:assign({checkpoint:({event:e})=>e.checkpoint,step:({event:e})=>e.step})}}},Stopped:{type:"final"}}}),it={Init:tt,PreparingForStep:ot,GeneratingToolCall:Qe,CallingTool:Ve,ResolvingToolResult:X,ResolvingThought:st,ResolvingPdfFile:rt,ResolvingImageFile:nt,GeneratingRunResult:He,CallingInteractiveTool:Je,CallingDelegate:qe,FinishingStep:Ye};var lt=z$1.object({model:z$1.string().optional(),temperature:z$1.number().optional(),maxSteps:z$1.number().optional(),maxRetries:z$1.number().optional(),experts:z$1.record(z$1.string(),z$1.object({version:z$1.string().optional(),minRuntimeVersion:z$1.string().optional(),description:z$1.string().optional(),instruction:z$1.string(),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[z$1.object({type:z$1.literal("mcpStdioSkill"),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional(),omit:z$1.array(z$1.string()).optional(),command:z$1.string(),packageName:z$1.string().optional(),args:z$1.array(z$1.string()).optional(),requiredEnv:z$1.array(z$1.string()).optional()}),z$1.object({type:z$1.literal("mcpSseSkill"),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional(),omit:z$1.array(z$1.string()).optional(),endpoint:z$1.string()}),z$1.object({type:z$1.literal("interactiveSkill"),description:z$1.string().optional(),rule:z$1.string().optional(),tools:z$1.record(z$1.string(),z$1.object({description:z$1.string().optional(),inputJsonSchema:z$1.string()}))})])).optional(),delegates:z$1.array(z$1.string()).optional()})).optional()});async function Br(e,t){let o=ke.parse(e),r=t?.eventListener??se,a=t?.retrieveCheckpoint??De,p=t?.storeCheckpoint??Oe,m=new V;m.subscribe(r);let{setting:s,checkpoint:g}=o;if(s.workspace){if(!pe.isAbsolute(s.workspace))throw new Error(`Workspace path must be absolute: ${s.workspace}`);process.chdir(s.workspace);}for(await Po(s);;){let{expertToRun:f,experts:d}=await Ro(s);So(f.name,d,s);let P=await Ae(f,d),R=createActor(at,{input:{setting:{...s,experts:d},initialCheckpoint:g??{id:createId(),runId:s.runId,expert:{key:s.expertKey,name:f.name,version:f.version},stepNumber:1,status:"init",messages:[],usage:H()},eventListener:r,skillManagers:P}}),h=await new Promise((S,j)=>{R.subscribe(async M=>{try{if(M.value==="Stopped"){let{checkpoint:T,skillManagers:ee}=M.context;if(!T)throw new Error("Checkpoint is undefined");await Ge(ee),S(T);}else {let T=await it[M.value](M.context);"checkpoint"in T&&await p(T.checkpoint,T.timestamp),await m.emit(T),R.send(T);}}catch(T){j(T);}}),R.start();});switch(h.status){case "completed":{if(h.delegatedBy){let{messages:S,delegatedBy:j}=h,{expert:M,toolCallId:T,toolName:ee,checkpointId:ct}=j,ce=S[S.length-1];if(ce.type!=="expertMessage")throw new Error("Delegation error: delegation result message is incorrect");let me=ce.contents.find(mt=>mt.type==="textPart");if(!me)throw new Error("Delegation error: delegation result message does not contain a text");s={...s,expertKey:M.key,input:{interactiveToolCallResult:{toolCallId:T,toolName:ee,text:me.text}}},g={...await a(s.runId,ct),id:createId(),stepNumber:h.stepNumber+1,usage:h.usage};break}return h}case "stoppedByInteractiveTool":return h;case "stoppedByDelegate":{if(!h.delegateTo)throw new Error("Delegation error: delegate to is undefined");let{expert:S,toolCallId:j,toolName:M,query:T}=h.delegateTo;s={...s,expertKey:S.key,input:{text:T}},g={id:createId(),runId:s.runId,status:"init",stepNumber:h.stepNumber+1,messages:[],expert:{key:S.key,name:S.name,version:S.version},delegatedBy:{expert:{key:f.key,name:f.name,version:f.version},toolCallId:j,toolName:M,checkpointId:h.id},usage:h.usage};break}case "stoppedByExceededMaxSteps":return h;case "stoppedByError":return h;default:throw new Error("Run stopped by unknown reason")}}}async function Ro(e){let{expertKey:t}=e,o={...e.experts},r=await ie(t,o);for(let a of r.delegates)if(!await ie(a,o))throw new Error(`Delegate ${a} not found`);return {expertToRun:r,experts:o}}function So(e,t,o){console.log("\u{1F99C} Starting Perstack \u{1F99C}"),console.log(`Expert To Run: ${e}`),console.log(`Experts: ${Object.keys(t).join(", ")}`),console.log(`Model: ${o.model}`),console.log(`Temperature: ${o.temperature}`),console.log(`Max Steps: ${o.maxSteps}`),console.log(`Max Retries: ${o.maxRetries}`),o.input.text&&console.log(`Query: ${o.input.text}`),o.input.interactiveToolCallResult&&(console.log(`Tool: ${o.input.interactiveToolCallResult.toolName}`),console.log(`Tool Call ID: ${o.input.interactiveToolCallResult.toolCallId}`),console.log(`Tool Result: ${o.input.interactiveToolCallResult.text}`));}async function Po(e){let t=O(e.runId);if(existsSync(t)){let o=pe.resolve(t,"run-setting.json"),r=JSON.parse(await readFile(o,"utf-8"));r.updatedAt=Date.now(),await writeFile(o,JSON.stringify(r,null,2),"utf-8");}else await mkdir(t,{recursive:true}),await writeFile(pe.resolve(t,"run-setting.json"),JSON.stringify(e,null,2),"utf-8");}function O(e){return `${process.cwd()}/perstack/runs/${e}`}async function zr(e){let t=ko.parse(e??"");return lt.parse(t)}var Ar=z$1.object({expertKey:z$1.string(),query:z$1.string(),options:z$1.object({config:z$1.string().optional(),model:z$1.string().optional(),temperature:z$1.string().optional().transform(e=>{if(e===void 0)return;let t=Number.parseFloat(e);if(!Number.isNaN(t))return t}),maxSteps:z$1.string().optional().transform(e=>{if(e===void 0)return;let t=Number.parseInt(e);if(!Number.isNaN(t))return t}),maxRetries:z$1.string().optional().transform(e=>{if(e===void 0)return;let t=Number.parseInt(e);if(!Number.isNaN(t))return t}),runId:z$1.string().optional()})});export{oe as CheckpointSchema,Ft as CheckpointStatusSchema,wt as ExpertMessageSchema,J as ExpertSchema,Rt as FileBinaryPartSchema,Tt as FileInlinePartSchema,kt as FileUrlPartSchema,xt as ImageBinaryPartSchema,fe as ImageInlinePartSchema,yt as ImageUrlPartSchema,vt as InstructionMessageSchema,q as InteractiveSkillSchema,ye as InteractiveToolSchema,K as McpSseSkillSchema,G as McpStdioSkillSchema,he as MessageSchema,lt as PerstackConfigSchema,_e as RegistryV1ExpertsGetResponseSchema,Ar as RunInputSchema,ke as RunParamsSchema,it as StateMachineLogics,_ as TextPartSchema,St as ToolCallPartSchema,It as ToolMessageSchema,Pt as ToolResultPartSchema,Nt as UsageSchema,Ct as UserMessageSchema,Me as attemptCompletion,Pe as callDelegate,Se as callInteractiveTool,Re as callTool,Ee as completeRun,Fe as continueToNextStep,k as createEvent,se as defaultEventListener,D as expertKeyRegex,Mt as expertNameRegex,$ as finishToolCall,O as getRunDir,$t as maxNameLength,zr as parseConfig,jo as parseExpertKey,Ie as resolveImageFile,we as resolvePdfFile,Ce as resolveThought,ve as resolveToolResult,re as retry,Br as run,at as runtimeStateMachine,Uo as skillNameRegex,Te as startGeneration,ne as startRun,$e as stopRunByDelegate,Ne as stopRunByExceededMaxSteps,be as stopRunByInteractiveTool,bt as tagNameRegex,Et as versionRegex};//# sourceMappingURL=index.js.map
|
|
80
80
|
//# sourceMappingURL=index.js.map
|