@makaio/framework 1.0.0-dev-1783615060726 → 1.0.0-dev-1783705652236
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/.makaio-build.json +2 -2
- package/dist/adapter-CA8rPIUz.mjs +1 -0
- package/dist/adapters/config/index.d.mts +1 -1
- package/dist/adapters/index.d.mts +186 -8
- package/dist/adapters/index.mjs +6 -6
- package/dist/bus/index.mjs +1 -1
- package/dist/client-DaR4mzqn.mjs +1 -0
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/index.mjs +1 -1
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +2 -2
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/extension/index.d.mts +2 -2
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +97 -45
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +3 -3
- package/dist/contracts/session/index.d.mts +3 -3
- package/dist/contracts/session/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +3 -3
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/{definition-DePb3ke-.d.mts → definition-s9PIua2B.d.mts} +1 -1
- package/dist/drizzle/0024_external_settlement_fingerprint.sql +1 -0
- package/dist/drizzle/0025_external_registration_frame.sql +1 -0
- package/dist/drizzle/meta/_journal.json +14 -0
- package/dist/{index-BbQpQ1N3.d.mts → index-B2DjrVb8.d.mts} +84 -0
- package/dist/{index-DWu3qrwe.d.mts → index-B9d_8_V2.d.mts} +8 -8
- package/dist/{index-2fK9iSHI.d.mts → index-BWIkf5oJ.d.mts} +6 -6
- package/dist/{index-BSprsrul.d.mts → index-BcvG3wPv.d.mts} +96 -57
- package/dist/{index-CqCe7Phc.d.mts → index-BcwOnvUh.d.mts} +6 -6
- package/dist/{index-Qd1Qom8M.d.mts → index-D6aAzr32.d.mts} +4 -4
- package/dist/{index-D8wmMJLi.d.mts → index-DScUb-hF.d.mts} +1 -1
- package/dist/{index-DKaEpPFS.d.mts → index-DnnKUwHm.d.mts} +5 -5
- package/dist/{index-S7lj2TLp.d.mts → index-FFVwQMad.d.mts} +440 -60
- package/dist/{index-BMbmoarE.d.mts → index-O08Q2ikz.d.mts} +8 -8
- package/dist/{index-DZ14azod.d.mts → index-PIlYSC73.d.mts} +160 -1
- package/dist/loop-gate-handlers-o2B5FPdF.mjs +1 -0
- package/dist/{namespace-DuUCiVmK.d.mts → namespace-B4cV_pk3.d.mts} +6 -6
- package/dist/{namespace-Ceg3zkt2.d.mts → namespace-BGIeqwfU.d.mts} +20 -20
- package/dist/{namespace-Dc94fHZW.d.mts → namespace-D9PLFmPQ.d.mts} +9 -9
- package/dist/package-Co_GO3UD.mjs +7 -0
- package/dist/{package-B6mEMD8r.d.mts → package-DmVZxufT.d.mts} +1 -1
- package/dist/package.json +1 -1
- package/dist/{schema-B9goOieO.d.mts → schema-B5vHi7Uu.d.mts} +1 -1
- package/dist/{schemas-D512XweP.d.mts → schemas-CJ2JvA7d.d.mts} +3 -3
- package/dist/schemas-CVo8qAK-.mjs +1 -0
- package/dist/services/adapter-subsystem/index.d.mts +2 -2
- package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
- package/dist/services/execution-target/index.d.mts +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/index.d.mts +14 -14
- package/dist/services/session/index.d.mts +4 -4
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/session/storage/namespace.d.mts +1 -1
- package/dist/services/session/storage/schema.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +3 -3
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/session-DBfQkgdy.mjs +1 -0
- package/dist/{session-lineage-NBFNVkUE.d.mts → session-lineage-C1M7-O3C.d.mts} +1 -1
- package/dist/{transition-CmI3q3FA.d.mts → transition-OzGXyy3p.d.mts} +1 -1
- package/dist/{types-VwMx5_lS.d.mts → types-BrUOVfwe.d.mts} +26 -2
- package/dist/{types-Dhou-Itn.d.mts → types-CBLPaQXe.d.mts} +36 -22
- package/dist/workflow-C3dgVwTY.mjs +1 -0
- package/dist/workflow-engine/index.d.mts +289 -21
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
- package/package.json +1 -1
- package/dist/adapter-Lx6K7yQS.mjs +0 -1
- package/dist/client-l1Rq5p6X.mjs +0 -1
- package/dist/loop-gate-handlers-Bjmat-K3.mjs +0 -1
- package/dist/package-BQn_RTo7.mjs +0 -1
- package/dist/schemas-CkOigLAT.mjs +0 -1
- package/dist/session-D5rVMqmE.mjs +0 -1
- package/dist/workflow-C1z7I5CI.mjs +0 -1
|
@@ -202,7 +202,7 @@ declare const SessionStorageNamespace$1: {
|
|
|
202
202
|
tableName: "sessions";
|
|
203
203
|
dataType: "string";
|
|
204
204
|
columnType: "SQLiteText";
|
|
205
|
-
data: "fork" | "subagent" | "
|
|
205
|
+
data: "fork" | "subagent" | "branch" | "compress" | "rewrite" | "coordinator" | "aside";
|
|
206
206
|
driverParam: string;
|
|
207
207
|
notNull: false;
|
|
208
208
|
hasDefault: false;
|
|
@@ -1073,8 +1073,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1073
1073
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1074
1074
|
fork: "fork";
|
|
1075
1075
|
subagent: "subagent";
|
|
1076
|
-
compress: "compress";
|
|
1077
1076
|
branch: "branch";
|
|
1077
|
+
compress: "compress";
|
|
1078
1078
|
rewrite: "rewrite";
|
|
1079
1079
|
coordinator: "coordinator";
|
|
1080
1080
|
aside: "aside";
|
|
@@ -1195,8 +1195,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1195
1195
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1196
1196
|
fork: "fork";
|
|
1197
1197
|
subagent: "subagent";
|
|
1198
|
-
compress: "compress";
|
|
1199
1198
|
branch: "branch";
|
|
1199
|
+
compress: "compress";
|
|
1200
1200
|
rewrite: "rewrite";
|
|
1201
1201
|
coordinator: "coordinator";
|
|
1202
1202
|
aside: "aside";
|
|
@@ -1342,8 +1342,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1342
1342
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1343
1343
|
fork: "fork";
|
|
1344
1344
|
subagent: "subagent";
|
|
1345
|
-
compress: "compress";
|
|
1346
1345
|
branch: "branch";
|
|
1346
|
+
compress: "compress";
|
|
1347
1347
|
rewrite: "rewrite";
|
|
1348
1348
|
coordinator: "coordinator";
|
|
1349
1349
|
aside: "aside";
|
|
@@ -1425,8 +1425,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1425
1425
|
branchKind: _$zod.ZodNullable<_$zod.ZodEnum<{
|
|
1426
1426
|
fork: "fork";
|
|
1427
1427
|
subagent: "subagent";
|
|
1428
|
-
compress: "compress";
|
|
1429
1428
|
branch: "branch";
|
|
1429
|
+
compress: "compress";
|
|
1430
1430
|
rewrite: "rewrite";
|
|
1431
1431
|
coordinator: "coordinator";
|
|
1432
1432
|
aside: "aside";
|
|
@@ -1504,8 +1504,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1504
1504
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1505
1505
|
fork: "fork";
|
|
1506
1506
|
subagent: "subagent";
|
|
1507
|
-
compress: "compress";
|
|
1508
1507
|
branch: "branch";
|
|
1508
|
+
compress: "compress";
|
|
1509
1509
|
rewrite: "rewrite";
|
|
1510
1510
|
coordinator: "coordinator";
|
|
1511
1511
|
aside: "aside";
|
|
@@ -1594,8 +1594,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1594
1594
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1595
1595
|
fork: "fork";
|
|
1596
1596
|
subagent: "subagent";
|
|
1597
|
-
compress: "compress";
|
|
1598
1597
|
branch: "branch";
|
|
1598
|
+
compress: "compress";
|
|
1599
1599
|
rewrite: "rewrite";
|
|
1600
1600
|
coordinator: "coordinator";
|
|
1601
1601
|
aside: "aside";
|
|
@@ -1689,8 +1689,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1689
1689
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1690
1690
|
fork: "fork";
|
|
1691
1691
|
subagent: "subagent";
|
|
1692
|
-
compress: "compress";
|
|
1693
1692
|
branch: "branch";
|
|
1693
|
+
compress: "compress";
|
|
1694
1694
|
rewrite: "rewrite";
|
|
1695
1695
|
coordinator: "coordinator";
|
|
1696
1696
|
aside: "aside";
|
|
@@ -1946,8 +1946,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
1946
1946
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1947
1947
|
fork: "fork";
|
|
1948
1948
|
subagent: "subagent";
|
|
1949
|
-
compress: "compress";
|
|
1950
1949
|
branch: "branch";
|
|
1950
|
+
compress: "compress";
|
|
1951
1951
|
rewrite: "rewrite";
|
|
1952
1952
|
coordinator: "coordinator";
|
|
1953
1953
|
aside: "aside";
|
|
@@ -2075,8 +2075,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2075
2075
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2076
2076
|
fork: "fork";
|
|
2077
2077
|
subagent: "subagent";
|
|
2078
|
-
compress: "compress";
|
|
2079
2078
|
branch: "branch";
|
|
2079
|
+
compress: "compress";
|
|
2080
2080
|
rewrite: "rewrite";
|
|
2081
2081
|
coordinator: "coordinator";
|
|
2082
2082
|
aside: "aside";
|
|
@@ -2225,8 +2225,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2225
2225
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2226
2226
|
fork: "fork";
|
|
2227
2227
|
subagent: "subagent";
|
|
2228
|
-
compress: "compress";
|
|
2229
2228
|
branch: "branch";
|
|
2229
|
+
compress: "compress";
|
|
2230
2230
|
rewrite: "rewrite";
|
|
2231
2231
|
coordinator: "coordinator";
|
|
2232
2232
|
aside: "aside";
|
|
@@ -2347,8 +2347,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2347
2347
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2348
2348
|
fork: "fork";
|
|
2349
2349
|
subagent: "subagent";
|
|
2350
|
-
compress: "compress";
|
|
2351
2350
|
branch: "branch";
|
|
2351
|
+
compress: "compress";
|
|
2352
2352
|
rewrite: "rewrite";
|
|
2353
2353
|
coordinator: "coordinator";
|
|
2354
2354
|
aside: "aside";
|
|
@@ -2494,8 +2494,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2494
2494
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2495
2495
|
fork: "fork";
|
|
2496
2496
|
subagent: "subagent";
|
|
2497
|
-
compress: "compress";
|
|
2498
2497
|
branch: "branch";
|
|
2498
|
+
compress: "compress";
|
|
2499
2499
|
rewrite: "rewrite";
|
|
2500
2500
|
coordinator: "coordinator";
|
|
2501
2501
|
aside: "aside";
|
|
@@ -2577,8 +2577,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2577
2577
|
branchKind: _$zod.ZodNullable<_$zod.ZodEnum<{
|
|
2578
2578
|
fork: "fork";
|
|
2579
2579
|
subagent: "subagent";
|
|
2580
|
-
compress: "compress";
|
|
2581
2580
|
branch: "branch";
|
|
2581
|
+
compress: "compress";
|
|
2582
2582
|
rewrite: "rewrite";
|
|
2583
2583
|
coordinator: "coordinator";
|
|
2584
2584
|
aside: "aside";
|
|
@@ -2656,8 +2656,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2656
2656
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2657
2657
|
fork: "fork";
|
|
2658
2658
|
subagent: "subagent";
|
|
2659
|
-
compress: "compress";
|
|
2660
2659
|
branch: "branch";
|
|
2660
|
+
compress: "compress";
|
|
2661
2661
|
rewrite: "rewrite";
|
|
2662
2662
|
coordinator: "coordinator";
|
|
2663
2663
|
aside: "aside";
|
|
@@ -2746,8 +2746,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2746
2746
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2747
2747
|
fork: "fork";
|
|
2748
2748
|
subagent: "subagent";
|
|
2749
|
-
compress: "compress";
|
|
2750
2749
|
branch: "branch";
|
|
2750
|
+
compress: "compress";
|
|
2751
2751
|
rewrite: "rewrite";
|
|
2752
2752
|
coordinator: "coordinator";
|
|
2753
2753
|
aside: "aside";
|
|
@@ -2841,8 +2841,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
2841
2841
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
2842
2842
|
fork: "fork";
|
|
2843
2843
|
subagent: "subagent";
|
|
2844
|
-
compress: "compress";
|
|
2845
2844
|
branch: "branch";
|
|
2845
|
+
compress: "compress";
|
|
2846
2846
|
rewrite: "rewrite";
|
|
2847
2847
|
coordinator: "coordinator";
|
|
2848
2848
|
aside: "aside";
|
|
@@ -3098,8 +3098,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
3098
3098
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
3099
3099
|
fork: "fork";
|
|
3100
3100
|
subagent: "subagent";
|
|
3101
|
-
compress: "compress";
|
|
3102
3101
|
branch: "branch";
|
|
3102
|
+
compress: "compress";
|
|
3103
3103
|
rewrite: "rewrite";
|
|
3104
3104
|
coordinator: "coordinator";
|
|
3105
3105
|
aside: "aside";
|
|
@@ -3227,8 +3227,8 @@ declare const SessionStorageNamespace$1: {
|
|
|
3227
3227
|
branchKind: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
3228
3228
|
fork: "fork";
|
|
3229
3229
|
subagent: "subagent";
|
|
3230
|
-
compress: "compress";
|
|
3231
3230
|
branch: "branch";
|
|
3231
|
+
compress: "compress";
|
|
3232
3232
|
rewrite: "rewrite";
|
|
3233
3233
|
coordinator: "coordinator";
|
|
3234
3234
|
aside: "aside";
|
|
@@ -3357,7 +3357,7 @@ declare const SessionStorageNamespace$1: {
|
|
|
3357
3357
|
contextInheritance?: "none" | "parent-history" | undefined;
|
|
3358
3358
|
rootSessionId?: string | undefined;
|
|
3359
3359
|
forkPointMessageId?: string | undefined;
|
|
3360
|
-
branchKind?: "fork" | "subagent" | "
|
|
3360
|
+
branchKind?: "fork" | "subagent" | "branch" | "compress" | "rewrite" | "coordinator" | "aside" | undefined;
|
|
3361
3361
|
adapterName?: string | undefined;
|
|
3362
3362
|
adapterSessionId?: string | undefined;
|
|
3363
3363
|
adapterId?: string | undefined;
|
|
@@ -546,8 +546,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
546
546
|
kind: _$zod.ZodEnum<{
|
|
547
547
|
fork: "fork";
|
|
548
548
|
subagent: "subagent";
|
|
549
|
-
compress: "compress";
|
|
550
549
|
branch: "branch";
|
|
550
|
+
compress: "compress";
|
|
551
551
|
rewrite: "rewrite";
|
|
552
552
|
coordinator: "coordinator";
|
|
553
553
|
aside: "aside";
|
|
@@ -925,8 +925,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
925
925
|
kind: _$zod.ZodEnum<{
|
|
926
926
|
fork: "fork";
|
|
927
927
|
subagent: "subagent";
|
|
928
|
-
compress: "compress";
|
|
929
928
|
branch: "branch";
|
|
929
|
+
compress: "compress";
|
|
930
930
|
rewrite: "rewrite";
|
|
931
931
|
coordinator: "coordinator";
|
|
932
932
|
aside: "aside";
|
|
@@ -1294,8 +1294,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
1294
1294
|
kind: _$zod.ZodEnum<{
|
|
1295
1295
|
fork: "fork";
|
|
1296
1296
|
subagent: "subagent";
|
|
1297
|
-
compress: "compress";
|
|
1298
1297
|
branch: "branch";
|
|
1298
|
+
compress: "compress";
|
|
1299
1299
|
rewrite: "rewrite";
|
|
1300
1300
|
coordinator: "coordinator";
|
|
1301
1301
|
aside: "aside";
|
|
@@ -1671,8 +1671,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
1671
1671
|
kind: _$zod.ZodEnum<{
|
|
1672
1672
|
fork: "fork";
|
|
1673
1673
|
subagent: "subagent";
|
|
1674
|
-
compress: "compress";
|
|
1675
1674
|
branch: "branch";
|
|
1675
|
+
compress: "compress";
|
|
1676
1676
|
rewrite: "rewrite";
|
|
1677
1677
|
coordinator: "coordinator";
|
|
1678
1678
|
aside: "aside";
|
|
@@ -2036,8 +2036,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
2036
2036
|
kind: _$zod.ZodEnum<{
|
|
2037
2037
|
fork: "fork";
|
|
2038
2038
|
subagent: "subagent";
|
|
2039
|
-
compress: "compress";
|
|
2040
2039
|
branch: "branch";
|
|
2040
|
+
compress: "compress";
|
|
2041
2041
|
rewrite: "rewrite";
|
|
2042
2042
|
coordinator: "coordinator";
|
|
2043
2043
|
aside: "aside";
|
|
@@ -2415,8 +2415,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
2415
2415
|
kind: _$zod.ZodEnum<{
|
|
2416
2416
|
fork: "fork";
|
|
2417
2417
|
subagent: "subagent";
|
|
2418
|
-
compress: "compress";
|
|
2419
2418
|
branch: "branch";
|
|
2419
|
+
compress: "compress";
|
|
2420
2420
|
rewrite: "rewrite";
|
|
2421
2421
|
coordinator: "coordinator";
|
|
2422
2422
|
aside: "aside";
|
|
@@ -2784,8 +2784,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
2784
2784
|
kind: _$zod.ZodEnum<{
|
|
2785
2785
|
fork: "fork";
|
|
2786
2786
|
subagent: "subagent";
|
|
2787
|
-
compress: "compress";
|
|
2788
2787
|
branch: "branch";
|
|
2788
|
+
compress: "compress";
|
|
2789
2789
|
rewrite: "rewrite";
|
|
2790
2790
|
coordinator: "coordinator";
|
|
2791
2791
|
aside: "aside";
|
|
@@ -3161,8 +3161,8 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
3161
3161
|
kind: _$zod.ZodEnum<{
|
|
3162
3162
|
fork: "fork";
|
|
3163
3163
|
subagent: "subagent";
|
|
3164
|
-
compress: "compress";
|
|
3165
3164
|
branch: "branch";
|
|
3165
|
+
compress: "compress";
|
|
3166
3166
|
rewrite: "rewrite";
|
|
3167
3167
|
coordinator: "coordinator";
|
|
3168
3168
|
aside: "aside";
|
|
@@ -3480,7 +3480,7 @@ declare const SessionEventStorageNamespace$1: {
|
|
|
3480
3480
|
payload: {
|
|
3481
3481
|
childSessionId: string;
|
|
3482
3482
|
parentSessionId: string;
|
|
3483
|
-
kind: "fork" | "subagent" | "
|
|
3483
|
+
kind: "fork" | "subagent" | "branch" | "compress" | "rewrite" | "coordinator" | "aside";
|
|
3484
3484
|
forkPointMessageId?: string | undefined;
|
|
3485
3485
|
};
|
|
3486
3486
|
} | {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as ee,P as te,R as ne,S as re,T as ie,U as ae,V as oe,W as se,X as ce,Y as le,Z as m,_ as ue,a as de,b as fe,c as pe,d as me,f as he,g as ge,h as _e,j as ve,k as ye,l as be,m as h,n as xe,o as Se,p as Ce,q as we,r as Te,t as Ee,u as De,w as Oe,x as ke,y as Ae,z as je}from"./loop-gate-handlers-o2B5FPdF.mjs";import{matchesFilter as Me,matchesSubscription as Ne}from"@makaio/framework/bus";import{ArtifactSubjects as Pe,EXECUTION_LIST_DEFAULT_LIMIT as Fe,EXECUTION_LIST_MAX_LIMIT as g,EXECUTION_LIST_MIN_LIMIT as _,EXTERNAL_EXECUTION_ID_PREFIX as v,ExecutionHintsSchema as Ie,ExecutionsByArtifactRefsQuerySchema as Le,JsonPatchOperationSchema as Re,JsonValueSchema as ze,SessionSubjects as Be,WORKFLOW_CANCELLED_REASON as y,WorkLogFrameEntrySchema as Ve,WorkflowError as b,WorkflowErrorCode as He,WorkflowNamespace as Ue,WorkflowStepTypeSchema as We,WorkflowSubjects as x,createWorkflowCancelSubject as Ge,dep as Ke,extensionToken as qe,serializeArtifactRef as Je}from"@makaio/framework/contracts";import{BaseService as Ye}from"@makaio/framework/service-base";import{defineDialectSchema as Xe,executeTransaction as S,getDatabaseDialect as Ze,registerDrizzleHandlers as Qe,resolveSchema as C}from"@makaio/framework/storage/drizzle";import{and as w,asc as T,count as E,desc as D,eq as O,getTableColumns as $e,gte as et,isNotNull as tt,isNull as k,lt as nt,lte as rt,notInArray as it,or as at,sql as A,sum as j}from"drizzle-orm";import{compile as ot}from"@makaio/framework/expression";import*as st from"node:os";import{SessionToken as ct}from"@makaio/framework/services";const lt=ie.postgres,ut=a.postgres,dt=r.postgres,ft=d.postgres,pt=oe.postgres,mt=ye.postgres,ht=je.postgres,gt=le.postgres,_t=o.postgres,vt=ae.postgres,yt=we.postgres,bt=ve.postgres,xt=p.postgres,M=Xe({workflowDefinitions:Oe,workflowExecutions:te,workflowExecutionFrames:i,workflowGateInstances:c,workflowStepSpans:t,workflowExecutionLinks:ee,workflowRunContexts:ne,worklogSummaries:l,worklogFrameEntries:se,worklogArtifactWrites:s,worklogGateEvents:u,workflowExecutionState:e,workflowExecutionStateEvents:f},{workflowDefinitions:lt,workflowExecutions:ut,workflowExecutionFrames:dt,workflowGateInstances:ft,workflowStepSpans:pt,workflowExecutionLinks:mt,workflowRunContexts:ht,worklogSummaries:gt,worklogFrameEntries:_t,worklogArtifactWrites:vt,worklogGateEvents:yt,workflowExecutionState:bt,workflowExecutionStateEvents:xt});function N(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function St(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function Ct(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=N(t);return[O(e.scopeType,n),O(e.scopeKind,r),O(e.scopeId,i)]}function P(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:St(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executionHints:e.executionHints??void 0}}function wt(e,t){let n=N(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Tt(e,t){let{workflowDefinitions:r}=C(t,M),i=$e(r),a=e.on(n.get,async e=>{let n=await t.select().from(r).where(O(r.id,e.payload.id)).limit(1);e.setResult({workflow:n[0]?P(n[0]):null})}),o=e.on(n.set,async n=>{let a=n.payload.workflow,o=Date.now(),s=wt(a,o),c=await t.insert(r).values(s).onConflictDoNothing({target:r.id}).returning();if(c.length>0){await e.emit(m.definition.created,P(c[0])),n.setResult({id:a.id});return}let[l]=await t.update(r).set({name:s.name,root:s.root,updatedAt:o,createdAt:A`COALESCE(${i.createdAt}, ${o})`,description:s.description===null?A`${i.description}`:s.description,inputSchema:s.inputSchema===null?A`${i.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?A`${i.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?A`${i.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?A`${i.artifact}`:s.artifact,triggers:s.triggers===null?A`${i.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?A`${i.canvasLayout}`:s.canvasLayout,source:s.source===null?A`${i.source}`:s.source,executionHints:s.executionHints===null?A`${i.executionHints}`:s.executionHints,...N(a.scope)}).where(O(r.id,a.id)).returning();l&&await e.emit(m.definition.updated,P(l)),n.setResult({id:a.id})}),s=e.on(n.delete,async n=>{let i=(await t.delete(r).where(O(r.id,n.payload.id)).returning()).length>0;i&&await e.emit(m.definition.deleted,{id:n.payload.id}),n.setResult({deleted:i})}),c=e.on(n.list,async e=>{let n=e.payload,i=n.scope?Ct(r,n.scope):[],a=i.length>0?await t.select().from(r).where(w(...i)):await t.select().from(r);e.setResult({workflows:a.map(P)})});return()=>{a(),o(),s(),c()}}function Et(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function Dt(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function Ot(e,t){let{workflowExecutionFrames:r}=C(t,M),i=e.on(n.setFrame,async e=>{let{executionId:n,frame:i}=e.payload,a=Dt(n,i);await t.insert(r).values(a).onConflictDoUpdate({target:r.frameId,set:a}),e.setResult({frameId:i.frameId})}),a=e.on(n.getFrame,async e=>{let n=await t.select().from(r).where(O(r.frameId,e.payload.frameId)).limit(1);e.setResult({frame:n[0]?Et(n[0]):null})}),o=e.on(n.listFrames,async e=>{let n=await t.select().from(r).where(O(r.executionId,e.payload.executionId)).orderBy(T(r.startedAt),T(r.frameId));e.setResult({frames:n.map(Et)})});return()=>{i(),a(),o()}}function kt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function F(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},...e.reason===null?{}:{reason:e.reason},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function I(e){return{id:kt(e),executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,reason:e.reason??null,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function At(e,t,n,r){if(e===void 0&&t===void 0)throw Error(`Either executionId or status is required to list gate instances.`);let i=n??Fe;if(!Number.isInteger(i)||i<_||i>g)throw Error(`Gate instance list limit must be an integer between ${_} and ${g}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[O(r.executionId,e)],...t===void 0?[]:[O(r.status,t)]]}}function jt(e,t){let{workflowExecutions:r,workflowGateInstances:i}=C(t,M),a=e.on(n.setGateInstance,async e=>{let n=e.payload.gate,r=I(n);await t.insert(i).values(r).onConflictDoUpdate({target:i.id,set:r}),e.setResult({id:r.id})}),o=e.on(n.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,r=I(n),a=await t.update(i).set(r).where(w(O(i.id,r.id),O(i.status,`waiting`))).returning({id:i.id});e.setResult({accepted:a.length===1})}),s=e.on(n.getGateInstance,async e=>{let{executionId:n,nodeId:r,frameId:a}=e.payload,o=[O(i.executionId,n),O(i.nodeId,r)];a!==void 0&&o.push(O(i.frameId,a));let s=await t.select().from(i).where(w(...o)).limit(1);e.setResult({gate:s[0]?F(s[0]):null})}),c=e.on(n.listGateInstances,async e=>{let{executionId:n,status:r,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=At(n,r,a,i),c=await t.select().from(i).where(w(...s)).orderBy(D(i.createdAt),D(i.id)).limit(o);e.setResult({gates:c.map(F)})}),l=e.on(n.listPausedGateTimeouts,async e=>{let n=await t.select({gate:i}).from(i).innerJoin(r,O(i.executionId,r.id)).where(w(O(i.status,`waiting`),O(r.status,`paused`),tt(i.timeoutMs)));e.setResult({gates:n.map(e=>F(e.gate))})});return()=>{a(),o(),s(),c(),l()}}function Mt(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function Nt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Pt(e,t){let{workflowStepSpans:r,workflowExecutionLinks:i}=C(t,M),a=e.on(n.setSpan,async e=>{let{span:n}=e.payload;await t.insert(r).values(n).onConflictDoUpdate({target:[r.executionId,r.frameId],set:n}),e.setResult({id:`${n.executionId}:${n.frameId}`})}),o=e.on(n.listSpans,async e=>{let n=await t.select().from(r).where(O(r.executionId,e.payload.executionId)).orderBy(T(r.startedAt),T(r.stepId),T(r.frameId));e.setResult({spans:n.map(Mt)})}),s=e.on(n.setExecutionLink,async e=>{let{link:n}=e.payload;await t.insert(i).values(n).onConflictDoUpdate({target:[i.sourceExecutionId,i.targetExecutionId],set:n}),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),c=e.on(n.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:r}=e.payload;if(n===void 0&&r===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[O(i.sourceExecutionId,n)],...r===void 0?[]:[O(i.targetExecutionId,r)]],o=t.select().from(i).where(w(...a));e.setResult({links:(await o).map(Nt)})});return()=>{a(),o(),s(),c()}}function Ft(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function It(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function Lt(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:It(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:St(e),...e.executionHints===null?{}:{executionHints:e.executionHints},...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Rt(e){let t=Ft(e.source),n=N(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,artifactRef:e.artifactRef??null,executionHints:e.executionHints??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy}}async function zt(e,t,n){let r=Rt(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function Bt(e,t){let{workflowRunContexts:r}=C(t,M),i=e.on(n.setRunContext,async e=>{let n=e.payload.runContext;await zt(t,n,r),e.setResult({executionId:n.executionId})}),a=e.on(n.getRunContext,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(O(r.executionId,n)),a=i[0]?Lt(i[0]):null;e.setResult({runContext:a})});return()=>{i(),a()}}function L(e,t){return t===null?Ze(e)===`postgres`?A`'null'::jsonb`:A`'null'`:t}async function Vt(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=C(e,M),a=Date.now(),o=L(e,n);await S(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function Ht(e,t){let{workflowExecutionState:n}=C(e,M),r=(await e.select().from(n).where(O(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function Ut(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=C(e,M),i=Date.now(),a=L(e,t.nextValue);return S(e,async e=>{let o=(await e.select().from(n).where(O(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=ke(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(w(O(n.executionId,t.executionId),O(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function Wt(e,t){let r=e.on(n.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await Vt(t,n,r),e.setResult({})}),i=e.on(n.getState,async e=>{let{executionId:n}=e.payload,r=await Ht(t,n);e.setResult({state:r})}),a=e.on(n.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Ut(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{r(),i(),a()}}function Gt(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function Kt(e,t){let{worklogSummaries:n}=C(e,M);await e.insert(n).values(t).onConflictDoNothing()}async function qt(e,t){let{worklogSummaries:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:Jt(t),setWhere:it(n.status,[`completed`,`failed`,`cancelled`])})}function Jt(e){return{workflowId:e.workflowId,workflowName:e.workflowName,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,error:e.error,failedNodeId:e.failedNodeId}}async function R(e,t){let{worklogSummaries:n}=C(e,M),r=await e.select().from(n).where(O(n.executionId,t)).limit(1);return r[0]?Gt(r[0]):null}async function Yt(e,t={}){let{worklogSummaries:n}=C(e,M),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[O(n.workflowId,r)],...i===void 0?[]:[O(n.status,i)]],c=s.length>0?w(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(D(n.startedAt)).limit(a).offset(o),e.select({count:E()}).from(n).where(c)]);return{items:l.map(Gt),total:u[0]?.count??0}}async function Xt(e,t){let{worklogFrameEntries:n}=C(e,M);await e.insert(n).values(t).onConflictDoNothing()}async function Zt(e,t){let{worklogFrameEntries:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:it(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function z(e,t){let{worklogFrameEntries:n}=C(e,M);return(await e.select().from(n).where(O(n.frameId,t)).limit(1))[0]??null}async function Qt(e,t){let n=await z(e,t);return n===null?null:Ve.parse({executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??void 0,branchKey:n.branchKey??void 0,startedAt:n.startedAt??void 0,completedAt:n.completedAt??void 0,durationMs:n.durationMs??void 0,inputTokens:n.inputTokens??void 0,outputTokens:n.outputTokens??void 0,estimatedCost:n.estimatedCost??void 0,error:n.error??void 0})}async function $t(e,t){let{worklogArtifactWrites:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function en(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function B(e,t){let{worklogGateEvents:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function tn(e,t){let{worklogGateEvents:n}=C(e,M);return(await e.select().from(n).where(O(n.id,t)).limit(1))[0]??null}function V(e,t,n){return`${e}:${t}:${n}`}async function nn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(O(t.executionId,n)).returning();return r}async function rn(e,t,n){let[r]=await e.select({totalInputTokens:j(t.inputTokens),totalOutputTokens:j(t.outputTokens),totalEstimatedCost:j(t.estimatedCost),measuredInputTokens:E(t.inputTokens),measuredOutputTokens:E(t.outputTokens),measuredCosts:E(t.estimatedCost)}).from(t).where(O(t.executionId,n));return{totalInputTokens:Number(r?.totalInputTokens??0),totalOutputTokens:Number(r?.totalOutputTokens??0),totalEstimatedCost:Number(r?.totalEstimatedCost??0),hasMeasurements:Number(r?.measuredInputTokens??0)>0||Number(r?.measuredOutputTokens??0)>0||Number(r?.measuredCosts??0)>0}}function an(e){return e.hasMeasurements}async function on(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(O(t.executionId,n))}async function sn(e,t,n,r){let i=A`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=A`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=A`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=A`exists(
|
|
2
|
+
select 1 from ${n}
|
|
3
|
+
where ${n.executionId} = ${r}
|
|
4
|
+
and (${n.inputTokens} is not null
|
|
5
|
+
or ${n.outputTokens} is not null
|
|
6
|
+
or ${n.estimatedCost} is not null)
|
|
7
|
+
)`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(w(O(t.executionId,r),s))}async function cn(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=C(e,M);if(Ze(e)===`sqlite`){await sn(e,n,r,t);return}await S(e,async e=>{if(await nn(e,n,t)===void 0)return;let i=await rn(e,r,t);an(i)&&await on(e,n,t,i)})}async function ln(e,t={}){let{worklogSummaries:n}=C(e,M),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[O(n.workflowId,r)],...i===void 0?[]:[et(n.startedAt,i)],...a===void 0?[]:[rt(n.startedAt,a)]],s=o.length>0?w(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:E()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:j(n.durationMs),totalInputTokens:j(n.totalInputTokens),totalOutputTokens:j(n.totalOutputTokens),totalEstimatedCost:j(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function un(e,t,n,r,i){let a=await z(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(Pe.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function H(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function U(e,t){try{await e.emit(m.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const dn=new Set([`completed`,`failed`,`cancelled`]);function fn(e){return dn.has(e)}async function pn(e,t,n){await Kt(t,{executionId:n.executionId,workflowId:n.workflowId,workflowName:null,status:`running`,startedAt:n.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),await U(e,n.executionId)}async function mn(e,t,n){let r=n.completedAt??Date.now(),i=await R(t,n.executionId);i!==null&&fn(i.status)||(await qt(t,{executionId:n.executionId,workflowId:i?.workflowId??n.executionId,workflowName:i?.workflowName??null,status:`completed`,startedAt:i?.startedAt??r-n.totalDuration,completedAt:r,durationMs:n.totalDuration,totalInputTokens:i?.totalInputTokens??null,totalOutputTokens:i?.totalOutputTokens??null,totalEstimatedCost:i?.totalEstimatedCost??null,error:null,failedNodeId:null}),await U(e,n.executionId))}async function hn(e,t,n,r,i,a,o){let s=await R(t,n);if(s!==null&&fn(s.status))return;let c=s?.startedAt??o;await qt(t,{executionId:n,workflowId:s?.workflowId??n,workflowName:s?.workflowName??null,status:r,startedAt:c,completedAt:o,durationMs:o-c,totalInputTokens:s?.totalInputTokens??null,totalOutputTokens:s?.totalOutputTokens??null,totalEstimatedCost:s?.totalEstimatedCost??null,error:i,failedNodeId:a}),await U(e,n)}function gn(e,t){return[e.on(m.execution.started,async n=>{let{executionId:r}=n.payload;await H(`execution.started[${r}]`,()=>pn(e,t,n.payload))}),e.on(m.execution.completed,async n=>{let{executionId:r}=n.payload;await H(`execution.completed[${r}]`,()=>mn(e,t,n.payload))}),e.on(m.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await H(`execution.failed[${r}]`,()=>hn(e,t,r,`failed`,i,a??null,o))}),e.on(m.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await H(`execution.cancelled[${r}]`,()=>hn(e,t,r,`cancelled`,null,null,i))})]}const _n=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function vn(e){return _n.has(e)}function yn(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function bn(e,t,n,r,i,a,o){let s=o??Date.now(),c=await z(t,r);c!==null&&vn(c.status)||(await Zt(t,{frameId:r,executionId:n,...yn(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await cn(t,n),await U(e,n))}async function xn(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await z(t,r);l!==null&&vn(l.status)||(await Zt(t,{frameId:r,executionId:n,...yn(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await U(e,n))}function Sn(e,t){return[e.on(m.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await H(`frame.started[${i}]`,async()=>{await Xt(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await U(e,r)})}),e.on(m.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await H(`frame.completed[${i}]`,()=>bn(e,t,r,i,a,o,s))}),e.on(m.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await H(`frame.failed[${i}]`,()=>xn(e,t,r,i,a,o,s,c))})]}const Cn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function wn(e,t){return[e.on(m.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await H(`gate.suspended[${i}]`,async()=>{await B(t,{id:V(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await U(e,r)})}),e.on(m.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await H(`gate.resumed[${i}]`,async()=>{let n=V(r,a,i),s=await tn(t,n),c=Date.now();await B(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await U(e,r)})}),e.on(m.gate.resolved,async n=>Tn(n.payload,e,t)),e.on(m.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await H(`artifact.updated[${r}:${i}]`,async()=>{let n=await un(e,t,i,a,o);if(n===null)return;let s=Date.now();await $t(t,{id:en(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await U(e,r)})})]}async function Tn(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await H(`gate.resolved[${i}]`,async()=>{let s=V(r,a,i),c=await tn(n,s),l=Date.now();await B(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Cn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await U(t,r)})}function En(e,t){let n=[...gn(e,t),...Sn(e,t),...wn(e,t),e.on(m.worklog.get,async e=>{let{executionId:n}=e.payload,r=await R(t,n);e.setResult({summary:r})}),e.on(m.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await Qt(t,n);e.setResult({frame:r})}),e.on(m.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await Yt(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(m.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await ln(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function W(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>W(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&W(n[e],r[e]))}function Dn(e){return{executionId:e.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,status:e.status,attempt:e.attempt,iteration:e.iteration??null,branchKey:e.branchKey??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null,durationMs:e.durationMs??null,inputTokens:e.inputTokens??null,outputTokens:e.outputTokens??null,estimatedCost:e.estimatedCost??null,error:e.error??null}}function On(e,t){let n=e.frame;if(n!==void 0){let r=e.status===`failed`?e.error??null:null;if(n.executionId!==e.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);if(n.status!==e.status)throw Error(`settleExternalExecution requires frame.status to match status`);if(n.completedAt!==t)throw Error(`settleExternalExecution requires frame.completedAt to match completedAt`);if(n.durationMs!==t-n.startedAt)throw Error(`settleExternalExecution requires frame.durationMs to match its timestamps`);if((n.error??null)!==r)throw Error(`settleExternalExecution requires frame.error to match terminal error metadata`)}return JSON.stringify({version:1,status:e.status,completedAt:t,error:e.status===`failed`?e.error??null:null,reason:e.status===`cancelled`?e.reason??null:null,frame:n===void 0?null:{executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??null,branchKey:n.branchKey??null,startedAt:n.startedAt,completedAt:n.completedAt,durationMs:n.durationMs,error:n.status===`failed`?n.error??null:null}})}function kn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function An(e,t,n,r,i){let a=On(r,i);if(n.externalSettlementFingerprint!==null){kn(n.externalSettlementFingerprint,a,r.executionId);return}if(r.frame!==void 0)throw Error(`settleExternalExecution: frame presence conflicts with the legacy frame-less settlement for execution "${r.executionId}"`);let o=r.status===`failed`?r.error??null:null,s=r.status===`cancelled`?r.reason??null:null;if((await e.update(t).set({externalSettlementFingerprint:a}).where(w(O(t.id,r.executionId),k(t.externalSettlementFingerprint),O(t.status,r.status),O(t.completedAt,i),o===null?k(t.error):O(t.error,o),s===null?k(t.reason):O(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(O(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(G(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);kn(c.externalSettlementFingerprint,a,r.executionId)}function jn(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!W(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function G(e,t,n){let r=t.status===`failed`?t.error??null:null,i=t.status===`cancelled`?t.reason??null:null;if(e.status!==t.status||e.completedAt!==n||e.error!==r||e.reason!==i)throw e.status===t.status?Error(`settleExternalExecution: execution "${t.executionId}" conflicts with an existing terminal settlement`):Error(`settleExternalExecution: execution "${t.executionId}" cannot transition from status "${e.status}"`)}async function Mn(e,t,n){let r=await e.select().from(t).where(O(t.executionId,n.executionId)),i=r.find(e=>e.frameId===n.frame.frameId);if(i!==void 0)return i;if(r.length>0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" conflicts with the registered frame identity`);let[a]=await e.select().from(t).where(O(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function Nn(e,t,n,r){let i=Math.min(e.startedAt,r);return{executionId:e.id,workflowId:e.workflowId,workflowName:t?.workflowName??null,status:n.status,startedAt:i,completedAt:r,durationMs:r-i,totalInputTokens:t?.totalInputTokens??null,totalOutputTokens:t?.totalOutputTokens??null,totalEstimatedCost:t?.totalEstimatedCost??null,error:n.status===`failed`?n.error??null:null,failedNodeId:n.status===`failed`?n.frame?.nodeId??t?.failedNodeId??null:null}}function Pn(e,t){return Dn({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function Fn(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&W(e.inputs,t.inputs)&&W(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function In(e,t){if(e.workflowId!==t.workflowId||e.startedAt!==t.startedAt||e.executionId!==t.executionId)throw Error(`setExternalExecutionStart: WorkLog summary conflicts for execution "${t.executionId}"`)}function Ln(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!W(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function Rn(e,t,n,r){if(!t.id.startsWith(v))throw Error(`setExternalExecutionStart: execution "${t.id}" is not an external execution ID`);if(n!==void 0&&n.executionId!==t.id)throw Error(`setExternalExecutionStart requires frame.executionId to match execution.id`);let{workflowExecutions:i,worklogSummaries:a,worklogFrameEntries:o}=C(e,M),s={...r(t),externalRegistrationFrameId:n?.frameId??null},c={executionId:t.id,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt,completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null};await S(e,async e=>{let r=(await e.insert(i).values(s).onConflictDoNothing().returning({id:i.id})).length===0;if(r){let[n]=await e.select().from(i).where(O(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);Fn(n,s)}let[l]=await e.select().from(a).where(O(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):In(l,c),n!==void 0){let[i]=await e.select().from(o).where(O(o.frameId,n.frameId)).limit(1);if(i===void 0){if(r)throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);await e.insert(o).values(Dn(n))}else Ln(i,n)}})}async function zn(e,t,n,r,i){if(r.frame!==void 0){let n=await Mn(e,t,r);return n!==void 0&&jn(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(O(t.frameId,n.externalRegistrationFrameId)).limit(1);if(a===void 0||a.executionId!==n.id)throw Error(`settleExternalExecution: registered frame "${n.externalRegistrationFrameId}" is unavailable for execution "${n.id}"`);if(a.startedAt===null)throw Error(`settleExternalExecution: registered frame "${a.frameId}" has no start timestamp`);if(i<a.startedAt)throw Error(`settleExternalExecution: completedAt must not precede the registered frame start timestamp`);let o=We.parse(a.nodeType);return{frame:{executionId:a.executionId,frameId:a.frameId,nodeId:a.nodeId,nodeType:o,path:a.path,status:r.status,attempt:a.attempt,...a.iteration===null?{}:{iteration:a.iteration},...a.branchKey===null?{}:{branchKey:a.branchKey},startedAt:a.startedAt,completedAt:i,durationMs:i-a.startedAt,...r.status===`failed`&&r.error!==void 0?{error:r.error}:{}},existing:a}}async function Bn(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await nn(e,a,n.id),c=await zn(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Pn(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await rn(e,o,n.id),d=an(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Nn(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:Jt(p)}),d&&await on(e,a,n.id,u)}async function Vn(e,t){if(!t.executionId.startsWith(v))throw Error(`settleExternalExecution: execution "${t.executionId}" is engine-owned and must use the engine finalizer`);if(t.frame!==void 0&&t.frame.executionId!==t.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);let{workflowExecutions:n,worklogSummaries:r,worklogFrameEntries:i}=C(e,M);return S(e,async e=>{let[a]=await e.select().from(n).where(O(n.id,t.executionId)).limit(1);if(a===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" was not registered`);let o=t.completedAt??a.completedAt??Date.now();if(a.status===`running`){let r=On(t,o);if((await e.update(n).set({status:t.status,completedAt:o,error:t.status===`failed`?t.error??null:null,reason:t.status===`cancelled`?t.reason??null:null,externalSettlementFingerprint:r}).where(w(O(n.id,t.executionId),O(n.status,`running`),k(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(O(n.id,t.executionId)).limit(1);if(r===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" disappeared`);t.completedAt===void 0&&r.completedAt!==null&&(o=r.completedAt),G(r,t,o),await An(e,n,r,t,o)}}else G(a,t,o),await An(e,n,a,t,o);return await Bn(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function Hn(e,t,r){let i=e.on(n.setExternalExecutionStart,async n=>{let i=n.payload.execution,a=n.payload.frame;await Rn(t,i,a,r),await U(e,i.id),n.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),a=e.on(n.settleExternalExecution,async n=>{let r=await Vn(t,n.payload);await U(e,n.payload.executionId),n.setResult({success:r})});return()=>{i(),a()}}function Un(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,...e.artifactKind!==null&&e.artifactId!==null?{artifactRef:{kind:e.artifactKind,id:e.artifactId}}:{},scope:St(e)}}function K(e){let t=N(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,artifactKind:e.artifactRef?.kind??null,artifactId:e.artifactRef?.id??null,...t}}function Wn(e,t,n,r,i,a){let o=[...e?[O(a.workflowId,e)]:[],...n?[O(a.status,n)]:[],...i===void 0?[]:[O(a.artifactKind,i.kind),O(a.artifactId,i.id)]];if(t&&o.push(...Ct(a,t)),r){let e=at(nt(a.startedAt,r.startedAt),w(O(a.startedAt,r.startedAt),nt(a.id,r.id)));e&&o.push(e)}return o}async function Gn(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=C(e,M),u=K(t);await S(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(O(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await zt(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=L(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function Kn(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let{workflowExecutions:r,workflowGateInstances:i}=C(e,M),a=K(t),o=I(n);await S(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await e.insert(i).values(o).onConflictDoUpdate({target:i.id,set:o})})}async function qn(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=C(e,M);return S(e,async e=>{if((await e.select().from(i).where(O(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(w(O(a.executionId,t),O(a.status,`waiting`)))).map(e=>({...F(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(O(i.id,t));for(let t of o){let n=I(t);await e.update(a).set(n).where(O(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Jn(e,t,n,r,i,a){let{workflowExecutions:o}=C(e,M);return S(e,async e=>{if((await e.select({id:o.id}).from(o).where(O(o.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),r!==void 0&&(s.error=r),i!==void 0&&(s.reason=i),a!==void 0&&(s.completedAt=a),Object.keys(s).length>0&&await e.update(o).set(s).where(O(o.id,t)),!0})}function Yn(e,t){let{workflowExecutions:r}=C(t,M),i=e.on(n.getExecution,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(O(r.id,n));e.setResult({execution:i[0]?Un(i[0]):null})}),a=e.on(n.setExecution,async e=>{let n=e.payload.execution,i=K(n);await t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),e.setResult({id:n.id})}),o=e.on(n.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await Gn(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),s=e.on(n.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await Kn(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),c=e.on(n.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Jn(t,n,r,i,a,o);e.setResult({success:s})}),l=e.on(n.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await qn(t,n,r,i))});return()=>{i(),a(),o(),s(),c(),l()}}function Xn(e,t){let{workflowExecutions:r}=C(t,M),i=e.on(n.listExecutions,async e=>{let{workflowId:n,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(n===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=Wn(n,i,a,s,c,r),u=o??Fe;if(!Number.isInteger(u)||u<_||u>g)throw Error(`Execution list limit must be an integer between ${_} and ${g}.`);let d=await t.select().from(r).where(w(...l)).orderBy(D(r.startedAt),D(r.id)).limit(u);e.setResult({executions:d.map(Un)})}),a=e.on(n.listExecutionsByArtifactRefs,async e=>{let n=Le.safeParse(e.payload);if(!n.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${n.error.message}`);let{refs:i,limitPerRef:a}=n.data,o={};for(let e of i){let n=await t.select().from(r).where(w(O(r.artifactKind,e.kind),O(r.artifactId,e.id))).orderBy(D(r.startedAt),D(r.id)).limit(a);n.length>0&&(o[Je(e)]=n.map(Un))}e.setResult({executionsByRef:o})});return()=>{i(),a()}}function Zn(e,t){let n=Tt(e,t),r=Yn(e,t),i=Xn(e,t),a=Ot(e,t),o=jt(e,t),s=Pt(e,t),c=Bt(e,t),l=Wt(e,t),u=En(e,t),d=Hn(e,t,K);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d()}}function Qn(e){return e.startsWith(v)}function $n(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function er(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}function q(e,t){if(e.origin.local)return!0;let n=e.transport?.peer;return n?.authenticated!==!0||n.id!==t?!1:n.kind===`workflow-execution`?!0:n.kind===`e2e`&&n.encrypted===!0}async function tr(e,t){let{runContext:r}=await e.request(n.getRunContext,{executionId:t});if(r===null)throw Error(`Run context not found for execution: ${t}`);if(r.definitionSnapshot!==void 0)return r.definitionSnapshot;let{workflow:i}=await e.request(n.get,{id:r.workflowId});return i??void 0}function nr(e){return[e.on(m.getDefinition,async t=>{let r=await e.request(n.get,{id:t.payload.id});t.setResult(r)}),e.on(m.setDefinition,async t=>{let r=await e.request(n.set,{workflow:t.payload.workflow});t.setResult(r)}),e.on(m.deleteDefinition,async t=>{let r=await e.request(n.delete,{id:t.payload.id});t.setResult(r)}),e.on(m.listDefinitions,async t=>{let r=await e.request(n.list,t.payload);t.setResult(r)}),e.on(m.getExecution,async t=>{let r=await e.request(n.getExecution,{executionId:t.payload.executionId});t.setResult(r)}),e.on(m.listExecutions,async t=>{let r=await e.request(n.listExecutions,t.payload);t.setResult(r)}),e.on(m.listExecutionsByArtifactRefs,async t=>{let r=await e.request(n.listExecutionsByArtifactRefs,t.payload);t.setResult(r)}),e.on(m.listSpans,async t=>{let r=await e.request(n.listSpans,{executionId:t.payload.executionId});t.setResult(r)}),e.on(m.listFrames,async t=>{let r=await e.request(n.listFrames,{executionId:t.payload.executionId});t.setResult(r)}),e.on(m.listGateInstances,async t=>{let r=await e.request(n.listGateInstances,t.payload);t.setResult(r)}),e.on(m.setExecutionLink,async t=>{let r=await e.request(n.setExecutionLink,{link:t.payload.link});t.setResult(r)}),e.on(m.listExecutionLinks,async t=>{let r=await e.request(n.listExecutionLinks,t.payload);t.setResult(r)}),e.on(m.getRunContext,async t=>{let{executionId:r}=t.payload;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${r}`);let{runContext:i}=await e.request(n.getRunContext,{executionId:r});if(!i)throw Error(`Run context not found for execution: ${r}`);t.setResult(i)}),...rr(e)]}function rr(e){return[e.on(m.registerExternalExecution,async t=>{let r=ce.registerExternalExecution.request.parse(t.payload),{name:i,scope:a,input:o}=r;if(r.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let s=r.executionId??ue(`wfx-ext`);if(!Qn(s))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let c=r.startedAt??Date.now(),l={id:s,workflowId:i,status:`running`,inputs:o===void 0?{}:o,startedAt:c,scope:a??{type:`global`},...$n(r)},u=ir(s,c,r.frame),d=await e.request(n.setExternalExecutionStart,{execution:l,...u===void 0?{}:{frame:u}});t.setResult(d)}),e.on(m.completeExternalExecution,async t=>{let r=ce.completeExternalExecution.request.parse(t.payload),{executionId:i,status:a}=r;if(!q(t,i))throw Error(`Unauthorized: caller is not permitted to settle execution: ${i}`);if(!Qn(i))throw Error(`completeExternalExecution: execution "${i}" is engine-owned and must be completed through the engine finalizer, not this API`);let o=ar(r),s=await e.request(n.settleExternalExecution,{executionId:i,status:a,...er(r),...r.completedAt===void 0?{}:{completedAt:r.completedAt},...o===void 0?{}:{frame:o}});t.setResult({success:s.success})})]}function ir(e,t,n){if(n===void 0)return;let r=n.frameId??`${e}:${n.nodeId}`;return{executionId:e,frameId:r,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path??[r],status:`running`,attempt:n.attempt,...n.iteration===void 0?{}:{iteration:n.iteration},...n.branchKey===void 0?{}:{branchKey:n.branchKey},startedAt:n.startedAt??t}}function ar(e){if(e.frame===void 0)return;if(e.completedAt===void 0)throw Error(`completedAt is required when frame metadata is supplied`);let t=e.completedAt-e.frame.startedAt;if(t<0)throw Error(`completedAt must not precede frame.startedAt`);if(e.frame.durationMs!==void 0&&e.frame.durationMs!==t)throw Error(`frame.durationMs must equal completedAt - frame.startedAt`);return{executionId:e.executionId,frameId:e.frame.frameId,nodeId:e.frame.nodeId,nodeType:e.frame.nodeType,path:e.frame.path,status:e.status,attempt:e.frame.attempt,...e.frame.iteration===void 0?{}:{iteration:e.frame.iteration},...e.frame.branchKey===void 0?{}:{branchKey:e.frame.branchKey},startedAt:e.frame.startedAt,completedAt:e.completedAt,durationMs:t,...e.status===`failed`&&e.error!==void 0?{error:e.error}:{}}}function or(e){return[e.on(m.state.get,async t=>{let{executionId:r}=t.payload;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${r}`);let{state:i}=await e.request(n.getState,{executionId:r});if(i===null)throw Error(`no workflow state for execution ${r}`);t.setResult(i)}),e.on(m.state.patch,async t=>{let{executionId:r,expectedSequence:i,patch:a,nextValue:o}=t.payload;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${r}`);if(i===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=await tr(e,r);s!==void 0&&Ae(s,o,`next`),Re.array().parse(a);let c=await e.request(n.patchState,{executionId:r,expectedSequence:i,nextValue:o});e.emit(m.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}function sr(e,t){return[e.on(m.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}async function cr(e,t){let{runContext:r}=await e.bus.request(n.getRunContext,{executionId:t});if(r===null)throw new b(He.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return r}function lr(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function ur(e,t){let n=await cr(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.executionHints??(t.mode===`snapshot`?n.executionHints:void 0),c=t.scopeOverride??n.scope,l={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,executionHints:s,scopeOverride:c,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:lr(t.mode,t.reason)}]};return t.mode===`snapshot`?await mr(e,n,l):fr(n)?await hr(e,n,l):await pe(e,n.workflowId,l)}function dr(e,t){return fr(e)?t.id:e.workflowId}function fr(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function pr(e){let t=e.definitionSnapshot;if(t===void 0)throw new b(He.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function mr(e,t,n){let r=pr(t);return De(e,dr(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}async function hr(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`)return be(e,t.source.path,n);let r=pr(t);return De(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}var gr=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(n.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:r}=await this.bus.request(n.getExecution,{executionId:e.executionId});return r?.status===`running`?`retry`:r?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function _r(e){if(e!==void 0)return vr(e)?e:{}}function vr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function yr(e){if(e!==void 0)return ze.parse(e)}function br(e){if(e!==void 0)return Ie.parse(e)}function xr(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${st.homedir()}/.makaio`,os:Ce(process.platform),arch:process.arch}}function Sr(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{packages:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,context:xr(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Cr(e){return e?.status===`paused`}function wr(e){return e?.status===`waiting`}async function Tr(e,t,r,i,a,o,s){t.delete(a.id),r.delete(a.id),i.delete(a.id);try{await e.request(n.restorePausedGateResumeState,{execution:a,gate:o})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${s}' after resume launch failure:`,e)}}async function Er(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:r}=await e.request(n.listFrames,{executionId:t.executionId});if(r.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Dr(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Or(e,t){if(t.frameId!==void 0){let{gate:r}=await e.request(n.getGateInstance,t);return wr(r)?r:null}let{gates:r}=await e.request(n.listGateInstances,{executionId:t.executionId}),i=r.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return i.length===1?i[0]:null}var kr=class extends Ye{static storage={drizzle:Zn};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;workflowRunner;triggerTypeRegistry;constructor(e,t,n){super(e),this.config={...fe,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new gr(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async onInit(){this.registerExecutionHandlers();for(let e of nr(this.bus))this.addCleanup(e);for(let e of or(this.bus))this.addCleanup(e);for(let e of sr(this.bus,()=>this.triggerTypeRegistry))this.addCleanup(e);await this.rehydratePausedGateTimeouts()}async onDestroy(){let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await h(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveWorkflowContext:e=>xr(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(Be.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Sr(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(m.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s,executionHints:c}=e.payload;try{let l=await pe(this.buildStartDeps(),t,{input:yr(n),config:_r(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:br(c),scopeOverride:s});e.setResult({executionId:l})}catch(e){if(e instanceof b)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(m.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,executionHints:l,reason:u}=e.payload;try{let d=await ur(this.buildStartDeps(),{executionId:t,mode:n,input:yr(r),config:_r(i),parentSessionId:a,triggerPayload:o,artifactRef:s,executionHints:br(l),scopeOverride:c,reason:u});e.setResult({executionId:d})}catch(e){if(e instanceof b)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(m.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,triggerPayload:n,scope:r}=e.payload;try{let i=await be(this.buildStartDeps(),t,{triggerPayload:n,scopeOverride:r});e.setResult({executionId:i})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(m.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(Ge(`workflow.${t}.cancel`),{executionId:t,reason:n}).catch(e=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${t}:`,e)});let r=this.workflowAbortControllers.get(t);if(r){r.abort(n??y);let i=await h(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await h(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(m.gate.respond,async e=>{let{executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o}=e.payload,s=await this.respondToPausedGate({executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o});e.setResult({accepted:s})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(m.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(m.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(n.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Dr(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let r=new AbortController;this.workflowAbortControllers.set(e,r);try{let i;try{let n=await de({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Se(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,r.signal,void 0,n,{context:t.runContext.context,env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});Ee(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();i=await xe(t.workflow.root,a,o)}catch(n){if(r.signal.aborted||t.execution.status===`cancelled`){await h(this.buildFinalizerDeps(),e,y);return}let i=n instanceof Error?n.message:String(n);await _e(this.buildFinalizerDeps(),t.execution,e,i);return}let a=this.buildFinalizerDeps();i.status===`cancelled`||r.signal.aborted||t.execution.status===`cancelled`?await h(a,e,y):i.status===`failed`?await _e(a,t.execution,e,i.error):i.status===`paused`?(t.execution.status=`paused`,await this.bus.request(n.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await ge(a,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:r,frameId:i,resumeData:a,reason:o}=e,{execution:s}=await this.bus.request(n.getExecution,{executionId:t});if(!Cr(s))return!1;let c=await Or(this.bus,{executionId:t,nodeId:r,frameId:i});if(c===null||!Te(r,c.schema,a).valid)return!1;let{runContext:l}=await this.bus.request(n.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Er(this.bus,l);let{accepted:u}=await this.bus.request(n.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:a,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await Tr(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,r),e}return this.gateTimeoutScheduler.clear(t,r,c.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(n.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let r=t.definitionSnapshot??(await this.bus.request(n.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:i}=await this.bus.request(n.getExecution,{executionId:e});if(i===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(i.status!==`paused`)return!1;await Er(this.bus,t),await this.bus.request(n.setExecution,{execution:{...i,status:`running`}}),this.activeExecutions.set(e,{execution:{...i,status:`running`},workflow:r,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let a=he(t,r,{resume:!0}),o=me(this.buildStartDeps(),a).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,o),!0}};function Ar(e,t){try{return ot(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function jr(e){let t=e.indexOf(`.`),n=e.indexOf(`:`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function Mr(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var Nr=class{bus;cleanupFns=[];initialized=!1;triggerIndex=new Map;subscribedNamespaces=new Set;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(x.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(x.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(x.definition.deleted,e=>{this.removeWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),!1)}getTestState(){return{initialized:this.initialized,cleanupFns:[...this.cleanupFns],subscribedNamespaces:new Set(this.subscribedNamespaces)}}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(n.list,{});for(let t of e)this.indexWorkflow(t)}indexWorkflow(e){let t=e.triggers??[],n=[];for(let r of t){if(r.type!==`bus-event`)continue;let t=typeof r.filterExpression==`string`?Ar(r.filterExpression,e.id):void 0;typeof r.filterExpression==`string`&&t===void 0||(n.push({workflowId:e.id,subject:r.subject,filter:r.filter,compiledFilterExpr:t}),this.ensureNamespaceSubscribed(jr(r.subject)))}n.length>0&&this.triggerIndex.set(e.id,n)}removeWorkflow(e){this.triggerIndex.delete(e)}ensureNamespaceSubscribed(e){if(this.subscribedNamespaces.has(e))return;let t=Mr(e),n=this.bus.on(t,e=>{if(e.isRequest)return;let t=typeof e.payload==`object`&&e.payload!==null?e.payload:{};this.handleBusEvent(e.subject,t)});this.cleanupFns.push(n),this.subscribedNamespaces.add(e)}handleBusEvent(e,t){for(let n of this.triggerIndex.values())for(let r of n)if(Ne(e,r.subject)&&!(r.filter&&!Me(t,r.filter))){if(r.compiledFilterExpr){let n;try{n=r.compiledFilterExpr.evalSync({payload:t})}catch(n){console.error(`[BusEventTriggerEvaluator] filterExpression eval failed for workflow "${r.workflowId}" on subject "${e}" payload keys: [${Object.keys(t).join(`, `)}]`,n);continue}if(!n)continue}this.bus.request(x.start,{workflowId:r.workflowId,triggerPayload:t}).catch(t=>{console.error(`[BusEventTriggerEvaluator] Failed to start workflow "${r.workflowId}" triggered by "${e}":`,t)})}}};function J(e,t,n,r,i,a,o,s){return J.fromTZ(J.tp(e,t,n,r,i,a,o),s)}J.fromTZISO=(e,t,n)=>J.fromTZ(Fr(e,t),n),J.fromTZ=function(e,t){let n=new Date(Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)),r=Pr(e.tz,n),i=new Date(n.getTime()-r),a=Pr(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=Pr(e.tz,r);if(o-a===0||!t&&o-a>0)return r;if(t)throw Error(`Invalid date passed to fromTZ()`);return i}},J.toTZ=function(e,t){let n=e.toLocaleString(`en-US`,{timeZone:t}).replace(/[\u202f]/,` `),r=new Date(n);return{y:r.getFullYear(),m:r.getMonth()+1,d:r.getDate(),h:r.getHours(),i:r.getMinutes(),s:r.getSeconds(),tz:t}},J.tp=(e,t,n,r,i,a,o)=>({y:e,m:t,d:n,h:r,i,s:a,tz:o});function Pr(e,t=new Date){let n=t.toLocaleString(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).split(` `).slice(-1)[0],r=t.toLocaleString(`en-US`).replace(/[\u202f]/,` `);return Date.parse(`${r} GMT`)-Date.parse(`${r} ${n}`)}function Fr(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`minitz: Invalid ISO8601 passed to parser.`);let r=e.substring(9);return e.includes(`Z`)||r.includes(`-`)||r.includes(`+`)?J.tp(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):J.tp(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}J.minitz=J;var Ir=32,Y=31|Ir,Lr=[1,2,4,8,16],Rr=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(e,t){this.pattern=e,this.timezone=t,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.replace(/\s+/g,` `).split(` `);if(e.length<5||e.length>6)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five or six space separated parts are required.`);if(e.length===5&&e.unshift(`0`),e[3].indexOf(`L`)>=0&&(e[3]=e[3].replace(`L`,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.replaceAlphaDays(e[5])),e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0){let t=new Z(new Date,this.timezone).getDate(!0);e[0]=e[0].replace(`?`,t.getSeconds().toString()),e[1]=e[1].replace(`?`,t.getMinutes().toString()),e[2]=e[2].replace(`?`,t.getHours().toString()),this.starDOM||(e[3]=e[3].replace(`?`,t.getDate().toString())),e[4]=e[4].replace(`?`,(t.getMonth()+1).toString()),this.starDOW||(e[5]=e[5].replace(`?`,t.getDay().toString()))}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1),this.partToArray(`dayOfWeek`,e[5],0,Y),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth;if(t===``&&!a)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let o=t.split(`,`);if(o.length>1)for(let t=0;t<o.length;t++)this.partToArray(e,o[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=parseInt(i[0],10)+n;if(isNaN(a))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,a,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`&&(t<0||t>=12))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t);this[e][t]=n}handleRangeWithStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);if(isNaN(l))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(u))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(isNaN(d))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(d===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(d>this[t].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[t].length+`)`);if(l>u)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}return[n,r]}handleRange(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;if(isNaN(o))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(o>s)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);a[0]===``&&(a[0]=`*`);let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(s===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(s>this[t].length)throw TypeError(`CronPattern: Syntax error, max steps for part is (`+this[t].length+`)`);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();return t===`@yearly`||t===`@annually`?`0 0 1 1 *`:t===`@monthly`?`0 0 1 * *`:t===`@weekly`?`0 0 * * 0`:t===`@daily`?`0 0 * * *`:t===`@hourly`?`0 * * * *`:e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|Ir;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|Lr[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},zr=[31,28,31,30,31,30,31,31,30,31,30,31],X=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Z=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date)if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`);else if(t===void 0)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&Y&&Lr[a-1]&r)return!0;if(r&Ir){let r=new Date(Date.UTC(e,t+1,0)).getUTCDate();for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0)if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else{let t=J.toTZ(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.day>zr[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}else return!1}fromString(e){if(typeof this.tz==`number`){let t=J.fromTZISO(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(J.fromTZISO(e,this.tz))}findNext(e,t,n,r){let i=this[t],a;n.lastDayOfMonth&&(a=this.month===1?new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate():zr[this.month]);let o=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let s=this[t]+r;s<n[t].length;s++){let c=n[t][s];if(t===`day`&&n.lastDayOfMonth&&s-r==a&&(c=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(o+(s-r-1))%7];if(t&&t&Y)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,s-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);e.legacyMode&&!n.starDOM?c||=t:c&&=t}if(c)return this[t]=s-r,i===this[t]?1:2}return 3}recurse(e,t,n){let r=this.findNext(t,X[n][0],e,X[n][2]);if(r>1){let i=n+1;for(;i<X.length;)this[X[i][0]]=-X[i][2],i++;if(r===3)return this[X[n][1]]++,this[X[n][0]]=-X[n][2],this.apply(),this.recurse(e,t,0);if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=X.length?this:this.year>=3e3?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):J.fromTZ(J.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Br(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode=e.legacyMode===void 0?!0:e.legacyMode,e.paused=e.paused===void 0?!1:e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch===void 0?!1:e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.unref=e.unref===void 0?!1:e.unref,e.startAt&&=new Z(e.startAt,e.timezone),e.stopAt&&=new Z(e.stopAt,e.timezone),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);return e}function Q(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function Vr(e){return Q(e)}function Hr(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var Ur=30*1e3,$=[],Wr=class{name;options;_states;fn;constructor(e,t,n){let r,i;if(Q(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(Q(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=Br(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new Rr(`* * * * *`)},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Z(e,this.options.timezone||this.options.utcOffset):this._states.pattern=new Rr(e,this.options.timezone),this.name){if($.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);$.push(this)}return i!==void 0&&Vr(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?t.getDate(!1):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=[],r=t||this._states.currentRun||void 0;for(;e--&&(r=this.nextRun(r));)n.push(r);return n}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Z||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Z(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=$.indexOf(this);e>=0&&$.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>Ur&&(t=Ur),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&Hr(this._states.currentTimeout),this)}async _trigger(e){if(this._states.blocking=!0,this._states.currentRun=new Z(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){Q(this.options.catch)&&this.options.catch(e,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Z(e,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&Q(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Z(e,this.options.timezone||this.options.utcOffset),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Z(e,this.options.timezone||this.options.utcOffset);return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_calculatePreviousRun(e,t){let n=new Z(void 0,this.options.timezone||this.options.utcOffset),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Z(r,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function Gr(e,t){return`${e}:${t}`}function Kr(e){return e??`UTC`}var qr=class{bus;cleanupFns=[];initialized=!1;jobs=new Map;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(x.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(x.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(x.definition.deleted,e=>{this.unscheduleWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),!1)}activeJobCount(){return this.jobs.size}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(n.list,{});for(let t of e)this.scheduleWorkflow(t)}scheduleWorkflow(e){if(e.scope.type===`global`)return;let t=e.triggers??[];for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==`cron`)continue;let i=Gr(e.id,n);this.stopJob(i);try{let t=Kr(r.timezone),a=new Wr(r.schedule,{timezone:t},()=>{this.fireTrigger(e.id,n)});this.jobs.set(i,{workflowId:e.id,triggerIndex:n,job:a})}catch(t){console.warn(`[CronTriggerEvaluator] Skipping invalid cron trigger key="${i}" workflowId="${e.id}" triggerIndex=${n} schedule="${r.schedule}" timezone="${r.timezone??`UTC`}"`,t)}}}unscheduleWorkflow(e){for(let[t,n]of this.jobs)n.workflowId===e&&(n.job.stop(),this.jobs.delete(t))}stopJob(e){let t=this.jobs.get(e);t&&(t.job.stop(),this.jobs.delete(e))}stopAllJobs(){for(let e of this.jobs.values())e.job.stop();this.jobs.clear()}fireTrigger(e,t){this.bus.request(x.start,{workflowId:e,triggerPayload:{firedAt:Date.now(),triggerIndex:t}}).catch(n=>{console.error(`[CronTriggerEvaluator] Failed to start workflow "${e}" for cron trigger index ${t}:`,n)})}},Jr=class extends Ye{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new kr(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new Nr(e),this.cronTriggerEvaluator=new qr(e)}get executor(){return this.workflowExecutor}get cronTriggers(){return this.cronTriggerEvaluator}setTriggerTypeRegistry(e){this.workflowExecutor.setTriggerTypeRegistry(e)}getTriggerTypeRegistry(){return this.workflowExecutor.getTriggerTypeRegistry()}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.busEventTriggerEvaluator.init(),await this.cronTriggerEvaluator.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.cronTriggerEvaluator.destroy(),()=>this.busEventTriggerEvaluator.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const Yr=qe(`makaio.workflow-engine`);function Xr(e){return{name:Yr.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[Ke(ct.name)],critical:!0,namespaces:[Ue,re],storage:{registerHandlers:Qe(Zn)},create:t=>new Jr(t.bus,e)}}const Zr=Xr();export{kr as a,Vt as c,Jr as i,Ut as l,Xr as n,Zn as o,Zr as r,Ht as s,Yr as t};
|
|
@@ -16,7 +16,7 @@ import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
|
|
|
16
16
|
* - Span CRUD: setSpan, listSpans
|
|
17
17
|
* - Execution link CRUD: setExecutionLink, listExecutionLinks
|
|
18
18
|
* - Run context CRUD: setRunContext, getRunContext
|
|
19
|
-
* - WorkLog projection:
|
|
19
|
+
* - WorkLog projection: execution/frame reads, stats, and changed events
|
|
20
20
|
* @param bus - MakaioBus instance for message handling
|
|
21
21
|
* @param db - Drizzle database instance
|
|
22
22
|
* @returns Cleanup function to unregister all handlers
|
package/dist/package.json
CHANGED
|
@@ -385,7 +385,7 @@ declare const sessions: _$drizzle_orm_sqlite_core0.SQLiteTableWithColumns<{
|
|
|
385
385
|
tableName: "sessions";
|
|
386
386
|
dataType: "string";
|
|
387
387
|
columnType: "SQLiteText";
|
|
388
|
-
data: "fork" | "subagent" | "
|
|
388
|
+
data: "fork" | "subagent" | "branch" | "compress" | "rewrite" | "coordinator" | "aside";
|
|
389
389
|
driverParam: string;
|
|
390
390
|
notNull: false;
|
|
391
391
|
hasDefault: false;
|
|
@@ -64,8 +64,8 @@ declare const SurfaceBindingRegistrationSchema: z.ZodObject<{
|
|
|
64
64
|
template: z.ZodString;
|
|
65
65
|
}, z.core.$strip>], "kind">;
|
|
66
66
|
appliesTo: z.ZodArray<z.ZodEnum<{
|
|
67
|
-
artifact: "artifact";
|
|
68
67
|
workpiece: "workpiece";
|
|
68
|
+
artifact: "artifact";
|
|
69
69
|
surface: "surface";
|
|
70
70
|
}>>;
|
|
71
71
|
valueMapping: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
@@ -108,8 +108,8 @@ declare const ArtifactProjectionPolicySchema: z.ZodObject<{
|
|
|
108
108
|
comment: "comment";
|
|
109
109
|
}>;
|
|
110
110
|
defaultRole: z.ZodOptional<z.ZodEnum<{
|
|
111
|
-
artifact: "artifact";
|
|
112
111
|
workpiece: "workpiece";
|
|
112
|
+
artifact: "artifact";
|
|
113
113
|
}>>;
|
|
114
114
|
semanticEvents: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
115
115
|
created: "created";
|
|
@@ -141,8 +141,8 @@ declare const ArtifactMaterializationRefSchema: z.ZodObject<{
|
|
|
141
141
|
externalId: z.ZodString;
|
|
142
142
|
externalUrl: z.ZodOptional<z.ZodString>;
|
|
143
143
|
surfaceRole: z.ZodEnum<{
|
|
144
|
-
artifact: "artifact";
|
|
145
144
|
workpiece: "workpiece";
|
|
145
|
+
artifact: "artifact";
|
|
146
146
|
}>;
|
|
147
147
|
lastSyncedRevision: z.ZodOptional<z.ZodString>;
|
|
148
148
|
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,t}from"./json-value-DmU8ibo_.mjs";import{a as n,s as ee}from"./visibility-Cb62p9bv.mjs";import"./credential-ref-YWQQENEo.mjs";import{c as te,f as r,i as ne,o as i,p as a,r as re,s as ie}from"./shared-BVW-3Dhy.mjs";import{a as ae,f as oe,i as se,n as ce,r as o,t as le,u as ue}from"./compression-C5JAWdgZ.mjs";import{t as s}from"./provider-context-CqMgPOWF.mjs";import{t as de}from"./schemas-XeIBqwvE.mjs";import{r as fe}from"./profile-BMBXUqqh.mjs";import{i as c}from"./account-identity-C7Kx_ieU.mjs";import{SessionLineageSchema as pe}from"./contracts/adapter/schemas/session-lineage.mjs";import{z as l}from"zod";import{localSubject as me,observability as u}from"@makaio/framework/core";const d=l.object({adapterId:l.string(),adapterName:l.string()}),he=l.object({cwd:l.string().optional(),allowedTools:l.array(l.string()).optional(),disallowedTools:l.array(l.string()).optional(),allowedDirectories:l.array(l.string()).optional(),systemPrompt:r.optional()}),ge={request:l.object({adapterName:l.string().optional(),adapterId:l.string().optional()}).refine(e=>e.adapterName||e.adapterId,{message:`Either adapterName or adapterId must be provided`}),response:l.object({capabilities:l.array(l.string()),nativeTools:l.array(l.string())})},f=l.enum([`lead`,`member`]),p=l.enum([`fork`,`branch`,`subagent`,`compress`,`rewrite`,`coordinator`,`aside`]),m=l.enum([`parent-history`,`none`]),h=l.enum([`discovered`,`imported`,`tracking`]),g=l.object({sessionId:l.string(),title:l.string().nullable(),forkPointMessageId:l.string().nullable(),branchKind:p.nullable(),messageCount:l.number(),hasChildren:l.boolean(),spawningToolCallId:l.string().optional()}),_=l.object({fromMessageId:l.string(),toMessageId:l.string(),policy:l.enum([`verbatim`,`summarize`,`exclude`]),stripReasoning:l.boolean().optional(),stripToolOutputs:l.boolean().optional(),overrides:l.record(l.string(),l.literal(`exclude`)).optional(),summaryText:l.string().optional()}),v=l.object({removedMessageIds:l.array(l.string()).optional(),appliedPipeline:l.array(l.object({actionId:l.string(),options:l.record(l.string(),l.unknown()).optional()})).optional(),segments:l.array(_).optional()}),_e=l.object({parentSessionId:l.string(),childSessionId:l.string(),summary:l.string().optional(),source:l.enum([`extension`,`user`,`system`]).optional(),extensionId:l.string().optional()}),ve=l.object({success:l.boolean(),handoff:l.string().optional()}),ye=l.object({parentSessionId:l.string(),childSessionId:l.string(),source:l.enum([`extension`,`user`,`system`]).optional(),extensionId:l.string().optional()}),be=l.object({success:l.boolean()}),xe=l.object({sessionId:l.string()}),Se=l.object({children:l.array(g)}),Ce=l.object({parentSessionId:l.string(),childSessionId:l.string(),reason:l.string()}),we=l.object({parentSessionId:l.string(),childSessionId:l.string(),forkPoint:l.string().optional()}),Te=l.object({parentSessionId:l.string(),childSessionId:l.string()}),Ee=l.object({parentSessionId:l.string(),childSessionId:l.string(),handoff:l.string()}),De=l.object({sessionId:l.string(),parentSessionId:l.string().optional()}),Oe=l.object({parentSessionId:l.string(),childSessionId:l.string(),result:l.unknown()}),ke=l.object({sessionId:l.string(),reason:l.string(),source:l.enum([`extension`,`user`,`system`]).optional(),extensionId:l.string().optional()}),Ae=l.object({sessionId:l.string(),pipeline:l.array(l.object({actionId:l.string(),options:l.record(l.string(),l.unknown()).optional()}))}),je=l.object({eventId:l.string(),contextJson:l.record(l.string(),l.unknown()),tokensBefore:l.number(),tokensAfter:l.number().optional()}),Me=l.object({sessionId:l.string(),childSessionId:l.string(),parentSessionId:l.string(),kind:p,forkPointMessageId:l.string().optional(),transforms:v.optional()}),Ne=l.object({sessionId:l.string(),childSessionId:l.string(),parentSessionId:l.string(),resultJson:l.string().optional(),resultMessageId:l.string().optional()}),Pe=l.object({sessionId:l.string(),summaryJson:l.string(),tokensBefore:l.number().optional(),tokensAfter:l.number().optional(),compressedMessageIds:l.array(l.string()).optional()}),y=l.object({sessionId:l.string(),parentSessionId:l.string().nullable(),branchKind:p.nullable(),createdAt:l.number(),originWindowId:l.string().optional()}),b=l.object({sessionId:l.string(),changedProperties:l.array(l.string())}),Fe={merge:{request:_e,response:ve},abandon:{request:ye,response:be},getChildren:{request:xe,response:Se},forking:Ce,forked:we,merging:Te,merged:Ee,abandoned:De,childCompleted:Oe,compressionRequested:ke,"branch.created":Me,"branch.merged":Ne,squash:Pe,created:y,updated:b,compress:{request:Ae,response:je}},x=l.enum([`adapter-unsupported`,`adapter-mismatch`,`no-adapter-session`,`missing-machine-id`,`machine-mismatch`,`cwd-mismatch`,`transforms-present`,`compression-present`,`connector-swap`,`mid-history-unsupported`,`hybrid-imported-orchestrated`,`native-attempt-failed`,`agent-already-started`,`fork-point-unresolvable`]),S=l.discriminatedUnion(`kind`,[l.object({kind:l.literal(`native`)}),l.object({kind:l.literal(`degrade`),reason:x}),l.object({kind:l.literal(`foreign`),machineId:l.string()})]),Ie=l.object({sourceSessionId:l.string(),sourceAdapterSessionId:l.string(),forkPointMessageId:l.string().optional(),targetWorkingDirectory:l.string().optional()}),C=l.string().regex(/^[\u0020-\u007e]*$/u,`Correlation identifiers must contain only printable ASCII characters`).trim().min(1).max(512),Le=l.object({sessionId:C.optional(),turnId:C.optional(),messageId:C.optional(),executionId:C.optional(),frameId:C.optional()}).strict(),Re=[`auto`,`systemPrompt`,`fullPrefix`],w=l.object({messageHistory:l.array(te).optional(),hasNewTransforms:l.boolean().optional(),hasCompression:l.boolean().optional(),extractedContext:l.unknown().optional(),isFirstTurn:l.boolean().optional(),hasConnectorSwap:l.boolean().optional(),cacheStrategy:l.enum(Re).optional(),turnContext:l.record(l.string(),e).optional(),requestCorrelation:Le.optional(),nativeLocality:S.optional(),nativeFork:Ie.optional()}),T=ne,E=l.enum([`user`,`assistant`]),D=l.enum([`voice`,`text`,`compact`]),O=l.object({messageId:l.string(),turnId:l.string().nullable(),sessionId:l.string(),role:E,contentText:l.string(),blocks:l.array(T),agentId:l.string().optional(),adapterSessionId:l.string().optional(),adapterMessageId:l.string().optional(),timestamp:l.number(),editOf:l.string().optional(),origin:D.optional()}),k=l.enum([`active`,`completed`,`error`]),A=l.object({inputTokens:l.number(),outputTokens:l.number(),cost:l.number().optional()}),j=l.object({total:A,byAgent:l.record(l.string(),A).optional()}),M=l.object({source:l.enum([`user`,`extension`,`system`]),sourceId:l.string().optional()}),N=l.object({turnId:l.string(),sessionId:l.string(),turnNumber:l.number().int().min(1),startedAt:l.number(),completedAt:l.number().optional(),status:k,error:l.string().optional(),usage:j.optional(),initiator:M.optional()}),P=l.enum([`sent`,`acknowledged`,`completed`]),ze=l.object({messageId:l.string(),agentId:l.string(),status:P,timestamp:l.number(),error:l.string().optional()}),F=l.enum([`idle`,`active`,`dead`,`disposed`]),I=l.object({agentId:l.string(),adapterId:l.string(),adapterName:l.string(),sessionId:l.string(),adapterSessionId:l.string().optional(),model:l.string().optional(),cwd:l.string().optional(),allowedDirectories:l.array(l.string()).optional(),providerConfigId:l.string().optional(),personaId:l.string().optional(),profileId:l.string().optional(),harnessId:l.string().optional(),clientId:l.string().optional(),compressionMode:le.optional(),role:f,status:F,createdAt:l.number(),lastActivityAt:l.number()}),L=l.record(l.string(),e),R=l.object({sessionId:l.string(),createdAt:l.number(),lastActivityAt:l.number(),agents:l.array(I),status:l.enum([`active`,`closed`,`archived`,`discovered`]),leadAgentId:l.string().optional(),parentSessionId:l.string().optional(),contextInheritance:m.optional(),rootSessionId:l.string().optional(),forkPointMessageId:l.string().optional(),branchKind:p.optional(),adapterName:l.string().optional(),adapterSessionId:l.string().optional(),adapterId:l.string().optional(),clientId:l.string().optional(),clientAccountId:l.string().optional(),lastClientIdentityObservation:c.optional(),isOrchestrated:l.boolean().optional(),title:l.string().optional(),summary:l.string().optional(),summaryUpdatedAt:l.number().optional(),isImported:l.boolean().optional(),forkTransforms:v.optional(),targetWorkingDirectory:l.string().optional(),executionTargetId:l.string().optional(),spawningToolCallId:l.string().optional(),approvalPolicyOverride:de.nullable().optional(),metadata:L.optional(),source:l.string().optional(),parentExternalSessionId:l.string().optional(),logFilePath:l.string().optional(),discoveredAt:l.number().optional(),importStatus:h.optional(),isSidechain:l.boolean().optional(),machineId:l.string().nullable().optional()}),z=l.object({messageCount:l.number(),firstUserMessage:l.string().nullable()}),B=R.extend({preview:z.optional()}),V=l.enum([`live`,`backfill`]),H=l.object({sessionId:l.string(),turnId:l.string(),turnNumber:l.number().int().min(1)}),U=H.extend({messageId:l.string()}),W=H.extend({success:l.boolean(),error:l.string().optional(),usage:j.optional(),initiator:M.optional(),ingestionMarker:V.optional()}),Be=se.safeExtend({kind:l.string().regex(/^(?!(?:adapter|canonical-model)$).+$/)}),Ve=l.union([o,ce,Be]),He=o.extend({providerContext:s.optional()}),Ue=l.object({sessionId:l.string(),agent:He,initialMessage:i.optional(),role:l.enum([`lead`,`member`]).optional()}),We=l.object({agentId:l.string(),adapterSessionId:l.string().optional(),role:l.enum([`lead`,`member`]),messageId:l.string().optional(),turnId:l.string().optional()}),G={sendMessage:{request:l.object({sessionId:l.string(),message:i,agent:Ve.optional(),agentIds:l.union([l.array(l.string()),l.literal(`all`)]).optional(),deliveryMode:l.enum([`enqueue`]).optional(),turnId:l.string().optional(),sessionContext:w.optional(),responseSchema:a.optional(),source:l.enum([`extension`,`user`,`system`]).optional(),extensionId:l.string().optional(),originWindowId:l.string().optional(),skipConnectorSwapWarning:l.boolean().optional(),origin:D.optional()}),response:l.object({messageId:l.string(),turnId:l.string(),sessionId:l.string()})},"agent.attach":{request:l.object({sessionId:l.string(),agent:ae,initialMessage:i.optional(),role:l.enum([`lead`,`member`]).optional()}),response:l.object({agentId:l.string(),adapterSessionId:l.string().optional(),role:l.enum([`lead`,`member`]),messageId:l.string().optional(),turnId:l.string().optional()})},"agent.attachResolved":me({request:Ue,response:We}),"turn.started":H.extend({messageId:l.string(),agentIds:l.array(l.string()),initiator:M.optional(),ingestionMarker:V.optional()}),"turn.completed":W,"turn.await":{request:l.object({sessionId:l.string(),turnId:l.string(),timeoutMs:l.number().int().positive()}),response:l.object({completion:W})},"user_message.sent":U.extend({content:i,agentIds:l.array(l.string()),source:l.enum([`extension`,`user`,`system`]).optional(),origin:D.optional()}),"user_message.acknowledged":U.extend({agentId:l.string()}),"user_message.completed":U.extend({agentId:l.string(),outcome:ie,supersededBy:l.string().optional(),mergedInto:l.string().optional(),error:l.string().optional()}),fork:{request:l.object({sourceSessionId:l.string(),fromMessageId:l.string().optional(),name:l.string().optional(),branchKind:l.enum([`fork`,`branch`,`aside`]).optional(),transforms:v.optional(),targetWorkingDirectory:l.string().optional(),metadata:L.optional(),existingSessionId:l.string().optional()}),response:l.object({sessionId:l.string()})}},Ge=l.discriminatedUnion(`success`,[l.object({agentId:l.string(),adapterId:l.string(),success:l.literal(!0)}),l.object({agentId:l.string(),adapterId:l.string(),success:l.literal(!1),error:l.string()})]),K=l.object({sessionId:l.string().optional(),parentSessionId:l.string().optional(),contextInheritance:m.optional(),forkPointMessageId:l.string().optional(),branchKind:p.optional(),forkTransforms:v.optional(),title:l.string().optional(),targetWorkingDirectory:l.string().optional(),executionTargetId:l.string().optional(),metadata:L.optional(),spawningToolCallId:l.string().optional(),originWindowId:l.string().optional(),machineId:l.string().nullable().optional()});function Ke(e,t){e.spawningToolCallId&&e.branchKind!==`subagent`&&t.addIssue({code:l.ZodIssueCode.custom,path:[`spawningToolCallId`],message:`spawningToolCallId is only valid for subagent sessions`})}const qe={list:{request:u.schema(l.object({status:l.enum([`active`,`closed`,`archived`,`discovered`,`all`]).optional(),limit:l.number().int().min(1).optional(),offset:u.hidden(l.number().int().min(0).optional()),includePreview:l.boolean().optional(),executionTargetId:l.string().optional()}),{traceAll:!0}),response:l.object({sessions:l.array(B),total:l.number()})},search:{request:l.object({query:l.string(),limit:l.number().int().min(1).optional(),status:l.enum([`active`,`closed`,`archived`,`discovered`,`all`]).optional(),isImported:l.boolean().optional()}),response:l.object({sessions:l.array(B),total:l.number()})},get:{request:l.object({sessionId:l.string()}),response:l.object({session:R.nullable()})},create:{request:K.superRefine(Ke),response:l.object({sessionId:l.string()})},close:{request:l.object({sessionId:l.string()}),response:l.object({success:l.boolean()})},resume:{request:l.object({sessionId:l.string()}),response:l.object({success:l.boolean()})},restartAgents:{request:l.object({sessionId:l.string(),machineId:l.string().optional()}),response:l.object({sessionId:l.string(),results:l.array(Ge)})},archive:{request:l.object({sessionId:l.string()}),response:l.object({success:l.boolean()})},purge:{request:l.object({sessionId:l.string()}),response:l.object({success:l.boolean(),eventsDeleted:l.number().optional(),error:l.string().optional()})},update:{request:l.object({sessionId:l.string(),executionTargetId:l.string().nullable().optional(),approvalPolicyOverride:de.nullable().optional(),title:l.string().optional(),metadata:L.nullable().optional()}),response:l.object({success:l.boolean()})},getByAdapterSessionId:{request:l.object({adapterSessionId:l.string()}),response:l.object({session:R.nullable()})},getStatusCounts:{request:l.object({}),response:l.object({all:l.number(),active:l.number(),closed:l.number(),archived:l.number(),discovered:l.number()})}},q=l.object({sessionId:l.string(),eventId:l.string(),timestamp:l.number()}),Je=l.discriminatedUnion(`type`,[q.extend({type:l.literal(`agent.added`),payload:l.object({sessionId:l.string(),adapterSessionId:l.string().optional(),agentId:l.string(),adapterId:l.string(),adapterName:l.string(),role:l.enum([`lead`,`member`]).optional(),model:l.string().optional(),cwd:l.string().optional()})}),q.extend({type:l.literal(`user_message.sent`),payload:G[`user_message.sent`]}),q.extend({type:l.literal(`user_message.acknowledged`),payload:G[`user_message.acknowledged`]}),q.extend({type:l.literal(`user_message.completed`),payload:G[`user_message.completed`]}),q.extend({type:l.literal(`turn.started`),payload:G[`turn.started`]}),q.extend({type:l.literal(`turn.completed`),payload:G[`turn.completed`]}),q.extend({type:l.literal(`message`),payload:l.object({messageId:l.string(),turnId:l.string().nullable(),role:l.enum([`user`,`assistant`])})}),q.extend({type:l.literal(`branch.created`),payload:l.object({childSessionId:l.string(),parentSessionId:l.string(),kind:p,forkPointMessageId:l.string().optional()})}),q.extend({type:l.literal(`branch.merged`),payload:l.object({childSessionId:l.string(),parentSessionId:l.string(),resultJson:l.string().optional(),resultMessageId:l.string().optional()})}),q.extend({type:l.literal(`squash`),payload:l.object({summaryJson:l.string(),tokensBefore:l.number().optional(),tokensAfter:l.number().optional(),compressedMessageIds:l.array(l.string()).optional()})}),q.extend({type:l.literal(`locality.degraded`),payload:l.discriminatedUnion(`verdictKind`,[l.object({intent:l.enum([`resume`,`fork`]),verdictKind:l.literal(`degrade`),reason:x,agentId:l.string().optional(),adapterId:l.string().optional(),turnId:l.string().optional()}),l.object({intent:l.enum([`resume`,`fork`]),verdictKind:l.literal(`foreign`),foreignMachineId:l.string(),agentId:l.string().optional(),adapterId:l.string().optional(),turnId:l.string().optional()})])})]),J=[`message`,`agent.added`,`turn.started`,`turn.completed`,`user_message.sent`,`user_message.acknowledged`,`user_message.completed`,`branch.created`,`branch.merged`,`squash`,`locality.degraded`],Ye=J,Xe=q.extend({type:l.string().refine(e=>!J.includes(e),{message:`Plugin session event type must not shadow a core event type.`}),payload:l.record(l.string(),l.unknown())}),Y=l.union([Je,Xe]),Ze=l.string(),Qe=l.object({sessionId:l.string().min(1),clientId:l.string().min(1),previousClientAccountId:l.string().min(1).nullable(),clientAccountId:l.string().min(1),source:l.string().min(1),observedAt:l.number().int().finite().nonnegative(),lastClientIdentityObservation:c}),$e=l.object({sessionId:l.string(),importStatus:h}),et={"agent.added":l.object({sessionId:l.string(),adapterSessionId:l.string().optional(),agentId:l.string(),adapterId:l.string(),adapterName:l.string(),role:f.optional(),model:l.string().optional(),cwd:l.string().optional()}),"agent.removed":l.object({sessionId:l.string(),agentId:l.string()}),closed:l.object({sessionId:l.string(),reason:l.string().optional()}),resumed:l.object({sessionId:l.string()}),archived:l.object({sessionId:l.string()}),purged:l.object({sessionId:l.string()}),compressed:l.object({sessionId:l.string(),eventId:l.string()}),"clientAccount.changed":Qe,"connectorSwap.editRequested":l.object({sessionId:l.string(),agentId:l.string(),previousCwd:l.string().optional(),newCwd:l.string().optional(),previousModel:l.string().optional(),newModel:l.string().optional()}),"locality.degraded":l.intersection(l.object({sessionId:l.string(),eventId:l.string(),timestamp:l.number()}),l.discriminatedUnion(`verdictKind`,[l.object({intent:l.enum([`resume`,`fork`]),verdictKind:l.literal(`degrade`),reason:x,agentId:l.string().optional(),adapterId:l.string().optional(),turnId:l.string().optional()}),l.object({intent:l.enum([`resume`,`fork`]),verdictKind:l.literal(`foreign`),foreignMachineId:l.string(),agentId:l.string().optional(),adapterId:l.string().optional(),turnId:l.string().optional()})])),getContextWindowState:{request:l.object({sessionId:l.string()}),response:l.object({state:l.object({currentTokens:l.number(),maxTokens:l.number(),percentage:l.number(),level:l.enum([`ok`,`warn`,`critical`]),lastUpdatedAt:l.number()}).nullable()})},importStatusChanged:$e,"import.completed":l.object({sessionId:l.string(),adapterSessionId:l.string(),source:l.string()}),event:Y},X=l.object({includeEvents:l.boolean().default(!1),includeToolOutputs:l.boolean().default(!1),includeAncestors:l.boolean().default(!0),includeChildren:l.boolean().default(!1)}),tt=`1.0`,Z=l.object({version:l.literal(`1.0`),exportedAt:l.number(),options:X,sessions:l.array(R),agents:l.array(I),messages:l.array(O),turns:l.array(N),events:l.array(Y).optional()});function nt(e){return Z.parse(e)}function rt(e){let t=Z.safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}const it={"snapshot.export":{request:l.object({sessionId:l.string(),options:X.optional()}),response:l.object({snapshot:Z})},"snapshot.import":{request:l.object({snapshot:Z,onConflict:l.enum([`fail`,`skip`,`overwrite`]).default(`fail`)}),response:l.object({imported:l.array(l.string()),skipped:l.array(l.string()),errors:l.array(l.object({sessionId:l.string(),error:l.string()}))})},"snapshot.validate":{request:l.object({snapshot:l.unknown()}),response:l.object({valid:l.boolean(),errors:l.array(l.string())})}},at={resolveAgentConfig:{request:l.object({selection:ae,projectId:l.string().optional()}),response:l.object({adapterName:l.string(),model:l.string().optional(),providerConfigId:l.string().optional(),reasoningEffort:n.optional(),supportedReasoningLevels:ee.optional(),systemPrompt:r.optional(),allowedTools:l.array(l.string()).optional(),disallowedTools:l.array(l.string()).optional(),allowedDirectories:l.array(l.string()).optional()})}},ot={resolveSystemPrompt:{request:l.object({sessionId:l.string(),personaId:l.string().optional(),profileId:l.string().optional()}),response:l.object({systemPrompt:l.string(),personaName:l.string().optional(),profileName:l.string().optional()})}},st={enrichContext:{request:l.object({sessionId:l.string()}),response:l.record(l.string(),l.unknown())}},ct={...qe,...et,...it,...Fe,...G,...at,...ot,...st},Q=l.object({adapterId:l.string(),harnessId:l.string().optional(),clientId:l.string().optional(),clientProfileName:fe.optional(),initialMessage:i.optional(),responseSchema:a.optional(),model:l.string().optional(),reasoningEffort:n.optional(),adapterConfig:t.optional(),env:l.record(l.string(),l.string()).optional(),role:f,sessionContext:w.optional(),mcpSessionContext:l.union([oe,ue]).optional(),providerContext:s.optional(),ephemeral:l.boolean().optional()}).merge(he),lt={request:l.union([Q.extend({mode:l.literal(`fork`),sessionId:l.string(),sourceSessionId:l.string(),sourceAdapterSessionId:l.string(),forkPointMessageId:l.string().optional(),targetWorkingDirectory:l.string().optional()}),Q.extend({mode:l.literal(`resume`),sessionId:l.string(),adapterSessionId:l.string()}),Q.extend({mode:l.literal(`create`).optional(),sessionId:l.string().optional()})]).superRefine((e,t)=>{let n=e.mode??`create`;e.ephemeral&&n!==`create`&&t.addIssue({code:l.ZodIssueCode.custom,path:[`ephemeral`],message:`ephemeral is only supported for create mode`}),e.ephemeral&&e.initialMessage===void 0&&t.addIssue({code:l.ZodIssueCode.custom,path:[`initialMessage`],message:`ephemeral startAgent requires initialMessage`})}),response:l.discriminatedUnion(`success`,[l.object({success:l.literal(!0),agentId:l.string(),adapterId:l.string(),adapterSessionId:l.string().optional(),sessionId:l.string(),messageId:l.string().optional()}),l.object({success:l.literal(!1),message:l.string()})])},ut={request:l.object({adapterId:l.string(),prompt:l.string(),model:l.string().optional(),systemPrompt:l.string().optional(),responseSchema:a.optional(),providerContext:s.optional()}),response:l.object({text:l.string(),usage:l.object({inputTokens:l.number(),outputTokens:l.number()}).optional()})},dt={request:l.object({adapterId:l.string()}),response:l.object({agents:l.array(l.object({agentId:l.string(),sessionId:l.string(),adapterSessionId:l.string().optional()}))})},ft={request:l.object({adapterId:l.string(),agentId:l.string()}),response:l.object({agent:l.object({agentId:l.string(),sessionId:l.string(),adapterSessionId:l.string().optional()}).nullable()})},pt={request:l.object({adapterId:l.string(),agentId:l.string()}),response:l.object({success:l.boolean()})},mt={request:l.object({adapterId:l.string(),agentId:l.string(),cwd:l.string().optional(),model:l.string().optional(),adapterSessionId:l.string().optional(),resumeAdapterSessionId:l.string().optional()}),response:l.object({})},ht={request:l.object({adapterName:l.string()}),response:l.object({found:l.boolean(),adapterName:l.string(),jsonSchema:l.record(l.string(),l.unknown()).nullable()})},gt=d.extend({agentId:l.string(),sessionId:l.string(),adapterSessionId:l.string().optional()}),_t=d.extend({adapterSessionId:l.string().optional(),sessionId:l.string(),model:l.string()}),vt=d.extend({sessionId:l.string(),adapterSessionId:l.string().optional(),totalInputTokens:l.number(),totalOutputTokens:l.number(),totalCalls:l.number()}),yt=d.extend({agentId:l.string(),sessionId:l.string(),adapterSessionId:l.string(),reason:l.string().optional()}),bt=d.extend({message:l.string(),timestamp:l.number(),level:l.enum([`debug`,`info`,`warn`,`error`]).optional()}),xt=d.extend({error:l.string(),sessionId:l.string().optional(),errorCategory:re.optional()}),St=d.extend({capabilities:l.array(l.string()),nativeTools:l.array(l.string()).optional()}),Ct=d.extend({provider:l.string(),quotaType:l.string(),limit:l.number(),used:l.number(),overage:l.number(),resetDate:l.string()}),wt=l.object({agentId:u.attribute(l.string(),`makaio.agent.id`),adapterId:u.attribute(l.string(),`makaio.adapter.id`),adapterName:u.attribute(l.string(),`makaio.adapter.name`),sessionId:u.attribute(l.string(),`makaio.session.id`).optional(),adapterSessionId:u.attribute(l.string(),`makaio.adapter.session_id`).optional(),messageId:u.attribute(l.string(),`makaio.message.id`).optional(),turnId:u.attribute(l.string(),`makaio.turn.id`).optional(),clientId:u.attribute(l.string(),`makaio.client.id`).optional(),providerConfigId:u.attribute(l.string(),`makaio.provider.config_id`).optional(),occurredAt:u.attribute(l.number(),`event.occurred_at`).optional()}),Tt=l.object({model:l.string().nullable(),cwd:l.string().nullable()}),Et=[`fresh`,`resume`,`fork`,`rotation`],$=l.enum(Et),Dt=wt.merge(Tt).extend({startMode:$}),Ot=d.merge(Tt).extend({adapterSessionId:l.string(),title:l.string().optional(),logFilePath:l.string().nullable().optional(),startedAt:l.number().finite().optional(),machineId:l.string().nullable().optional()}).and(pe);export{A as $,Qe as A,B,ot as C,X as D,Z as E,K as F,T as G,I as H,V as I,O as J,D as K,R as L,Y as M,Ye as N,rt as O,Ze as P,j as Q,z as R,st as S,tt as T,ze as U,F as V,P as W,N as X,M as Y,k as Z,ft as _,wt as a,S as at,lt as b,xt as c,y as ct,vt as d,f as dt,Re as et,_t as f,p as ft,pt as g,he as gt,mt as h,ge as ht,Dt as i,x as it,$e as j,nt as k,bt as l,b as lt,ht as m,m as mt,Et as n,Le as nt,Ct as o,v as ot,gt as p,h as pt,E as q,$ as r,Ie as rt,St as s,_ as st,Ot as t,w as tt,yt as u,g as ut,dt as v,at as w,ct as x,ut as y,L as z};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { S as ProviderConfigFileRecordSchema, _ as BindingRecord, a as CanonicalProviderConfigPatchSchema, b as EffectiveAdapterSchema, c as CreateCanonicalProviderConfigInputSchema, d as ProviderConfigFileSet, f as AdapterFileConfig, g as AdapterSubsystemSchemas, h as AdapterReadinessSchema, i as CanonicalProviderConfigPatch, l as AdapterFileConfigSet, m as AdapterReadiness, n as CanonicalProviderConfigCredentialRefsPayload, o as CreateCanonicalProviderConfigInput, p as AdapterFileConfigSchema, r as CanonicalProviderConfigCredentialRefsSchema, s as CreateCanonicalProviderConfigInputPayload, t as CanonicalProviderConfigCredentialRefs, u as IAdapterConfigRepository, v as BindingRecordSchema, x as ProviderConfigFileRecord, y as EffectiveAdapter } from "../../index-
|
|
2
|
-
import { n as AdapterSubsystemSubjects, t as AdapterSubsystemNamespace } from "../../namespace-
|
|
1
|
+
import { S as ProviderConfigFileRecordSchema, _ as BindingRecord, a as CanonicalProviderConfigPatchSchema, b as EffectiveAdapterSchema, c as CreateCanonicalProviderConfigInputSchema, d as ProviderConfigFileSet, f as AdapterFileConfig, g as AdapterSubsystemSchemas, h as AdapterReadinessSchema, i as CanonicalProviderConfigPatch, l as AdapterFileConfigSet, m as AdapterReadiness, n as CanonicalProviderConfigCredentialRefsPayload, o as CreateCanonicalProviderConfigInput, p as AdapterFileConfigSchema, r as CanonicalProviderConfigCredentialRefsSchema, s as CreateCanonicalProviderConfigInputPayload, t as CanonicalProviderConfigCredentialRefs, u as IAdapterConfigRepository, v as BindingRecordSchema, x as ProviderConfigFileRecord, y as EffectiveAdapter } from "../../index-D6aAzr32.mjs";
|
|
2
|
+
import { n as AdapterSubsystemSubjects, t as AdapterSubsystemNamespace } from "../../namespace-B4cV_pk3.mjs";
|
|
3
3
|
export { AdapterFileConfig, AdapterFileConfigSchema, AdapterFileConfigSet, AdapterReadiness, AdapterReadinessSchema, AdapterSubsystemNamespace, AdapterSubsystemSchemas, AdapterSubsystemSubjects, BindingRecord, BindingRecordSchema, CanonicalProviderConfigCredentialRefs, CanonicalProviderConfigCredentialRefsPayload, CanonicalProviderConfigCredentialRefsSchema, CanonicalProviderConfigPatch, CanonicalProviderConfigPatchSchema, CreateCanonicalProviderConfigInput, CreateCanonicalProviderConfigInputPayload, CreateCanonicalProviderConfigInputSchema, EffectiveAdapter, EffectiveAdapterSchema, IAdapterConfigRepository, ProviderConfigFileRecord, ProviderConfigFileRecordSchema, ProviderConfigFileSet };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as AdapterSubsystemSubjects, t as AdapterSubsystemNamespace } from "../../namespace-
|
|
1
|
+
import { n as AdapterSubsystemSubjects, t as AdapterSubsystemNamespace } from "../../namespace-B4cV_pk3.mjs";
|
|
2
2
|
export { AdapterSubsystemNamespace, AdapterSubsystemSubjects };
|