1
import { Argument, Command, Flag } from 'effect/unstable/cli';
2
import util from 'node:util';
3
-import { Cause, Context, Data, Effect, Exit, Fiber, Option, Result } from 'effect';
3
+import { Data, Effect, Context, Option, Result } from 'effect';
4
import { redact } from 'src/ui/redact';
5
import { parseJsonRecord, isPlainRecord } from 'src/utils/parse-json';
6
import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
7
import { requireAuth } from 'src/effects/require-auth';
8
import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
9
import {
10
- getCachedToolInputDefinition,
10
getOrFetchToolInputDefinition,
11
invalidateToolInputDefinition,
13
- refreshToolInputDefinitionIfVersionChanged,
12
ToolInputValidationError,
13
validateToolInputArguments,
14
validateToolInputArgumentsWithDefinition,
721
return { error: mapped.message, slug: slugValue };
722
});
723
726
-type CachedValidationDecision =
727
- { readonly status: 'valid' | 'stale' } | { readonly status: 'fail'; readonly error: unknown };
728
-
729
-type ValidationState = {
730
- readonly cacheHit: boolean;
731
- readonly validationGuard: Effect.Effect<never, unknown>;
732
- readonly awaitCachedValidationDecision: Effect.Effect<CachedValidationDecision, never> | null;
733
-};
734
-
735
-type CachedDefinition = {
736
- readonly schemaPath: string;
737
- readonly schema: Record<string, unknown>;
738
- readonly version: string | null;
739
-} | null;
740
-
741
-const validationGuardFromFiber = (validationFiber: Fiber.Fiber<unknown, unknown>) =>
742
- Fiber.await(validationFiber).pipe(
743
- Effect.flatMap(
744
- Exit.match({
745
- onFailure: cause => {
746
- const fail = Cause.findFail(cause);
747
- if (Result.isSuccess(fail) && fail.success.error instanceof ToolInputValidationError) {
748
- return Effect.failCause(cause);
749
- }
750
- return Effect.never;
751
- },
752
- onSuccess: () => Effect.never,
753
- })
754
- )
755
- );
756
-
757
-const spawnBackgroundValidationGuard = (params: {
758
- readonly slug: string;
759
- readonly args: Record<string, unknown>;
760
- readonly resolvedProject: {
761
- readonly orgId: string;
762
- readonly projectId: string;
763
- };
764
-}) =>
765
- Effect.gen(function* () {
766
- yield* perfDebugLog('execute.validation.background_spawn', { slug: params.slug });
767
- const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {
768
- orgId: params.resolvedProject.orgId,
769
- projectId: params.resolvedProject.projectId,
770
- }).pipe(Effect.forkDetach);
771
- yield* perfDebugLog('execute.validation.background_spawned', { slug: params.slug });
772
- return validationGuardFromFiber(validationFiber);
773
- });
774
-
775
-const initializeValidationState = (params: {
724
+// Gates the tool call: the request is only sent once the arguments pass. A
725
+// schema that cannot be loaded does not block the call, the server validates too.
726
+const validateToolInputBeforeExecute = (params: {
727
readonly slug: string;
728
readonly args: Record<string, unknown>;
778
- readonly cachedDefinition: CachedDefinition;
729
readonly resolvedProject: {
730
readonly orgId: string;
731
readonly projectId: string;
732
};
733
}) =>
784
- Effect.gen(function* () {
785
- if (!params.cachedDefinition) {
786
- yield* perfDebugLog('execute.validation.cache_miss', { slug: params.slug });
787
- return {
788
- cacheHit: false,
789
- validationGuard: Effect.never,
790
- awaitCachedValidationDecision: null,
791
- } satisfies ValidationState;
792
- }
793
- const cachedDefinition = params.cachedDefinition;
794
-
795
- yield* perfDebugLog('execute.validation.cache_hit', {
796
- slug: params.slug,
797
- cachedVersion: cachedDefinition.version,
798
- });
799
- const versionCheckFiber = yield* refreshToolInputDefinitionIfVersionChanged(
800
- params.slug,
801
- cachedDefinition.version,
802
- {
803
- orgId: params.resolvedProject.orgId,
804
- projectId: params.resolvedProject.projectId,
805
- }
806
- ).pipe(
807
- Effect.tap(result =>
808
- perfDebugLog('execute.validation.version_check_done', {
809
- slug: params.slug,
810
- cachedVersion: cachedDefinition.version,
811
- latestVersion: result.latestVersion,
812
- isStale: result.isStale,
813
- })
814
- ),
815
- Effect.option,
816
- Effect.forkDetach
817
- );
818
- const cachedValidationDecisionFiber = yield* Effect.gen(function* () {
819
- yield* perfDebugLog('execute.validation.cached_start', { slug: params.slug });
820
- const validationDecision = yield* validateToolInputArgumentsWithDefinition(
821
- params.slug,
822
- params.args,
823
- cachedDefinition
824
- ).pipe(
825
- Effect.match({
826
- onFailure: error => ({ status: 'fail', error }) satisfies CachedValidationDecision,
827
- onSuccess: () => ({ status: 'valid' }) satisfies CachedValidationDecision,
828
- })
829
- );
830
- yield* perfDebugLog('execute.validation.cached_end', {
831
- slug: params.slug,
832
- successful: validationDecision.status === 'valid',
833
- });
834
- if (validationDecision.status === 'valid') {
835
- return validationDecision;
836
- }
837
-
838
- const freshnessResult = yield* Fiber.join(versionCheckFiber);
839
- const isStale = Option.isSome(freshnessResult) && freshnessResult.value.isStale;
840
- yield* perfDebugLog('execute.validation.cached_failed', {
841
- slug: params.slug,
842
- cacheStillCurrent: !isStale,
843
- });
844
- return isStale
845
- ? ({ status: 'stale' } satisfies CachedValidationDecision)
846
- : validationDecision;
847
- }).pipe(Effect.forkDetach);
848
- const awaitCachedValidationDecision = Fiber.join(cachedValidationDecisionFiber);
849
-
850
- return {
851
- cacheHit: true,
852
- awaitCachedValidationDecision,
853
- validationGuard: awaitCachedValidationDecision.pipe(
854
- Effect.flatMap(decision => {
855
- if (decision.status === 'fail') {
856
- return Effect.fail(decision.error);
857
- }
858
-
859
- return Effect.never;
860
- })
861
- ),
862
- } satisfies ValidationState;
863
- });
734
+ validateToolInputArguments(params.slug, params.args, {
735
+ orgId: params.resolvedProject.orgId,
736
+ projectId: params.resolvedProject.projectId,
737
+ }).pipe(
738
+ Effect.asVoid,
739
+ Effect.catchIf(
740
+ error => !(error instanceof ToolInputValidationError),
741
+ () => perfDebugLog('execute.validation.schema_unavailable', { slug: params.slug })
742
+ )
743
+ );
744
745
type DryRunSummary = {
746
readonly successful: true;
1115
}) =>
1116
Effect.gen(function* () {
1117
const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
1238
- const cachedDefinition = verificationDisabled
1239
- ? null
1240
- : yield* getCachedToolInputDefinition(params.slug);
1241
- const validationState: ValidationState = verificationDisabled
1242
- ? ({
1243
- cacheHit: false,
1244
- validationGuard: Effect.never,
1245
- awaitCachedValidationDecision: null,
1246
- } satisfies ValidationState)
1247
- : yield* initializeValidationState({
1248
- slug: params.slug,
1249
- args: params.args,
1250
- cachedDefinition,
1251
- resolvedProject: params.resolvedProject,
1252
- });
1118
1119
yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
1120
Effect.gen(function* () {
1256
- let validationGuard = validationState.validationGuard;
1257
- if (!verificationDisabled && !validationState.cacheHit) {
1258
- validationGuard = yield* spawnBackgroundValidationGuard({
1259
- slug: params.slug,
1260
- args: params.args,
1261
- resolvedProject: params.resolvedProject,
1262
- });
1263
- }
1264
-
1121
if (params.dryRun) {
1122
const definition = verificationDisabled
1123
? null
1268
- : (cachedDefinition ??
1269
- (yield* getOrFetchToolInputDefinition(params.slug, {
1124
+ : yield* getOrFetchToolInputDefinition(params.slug, {
1125
orgId: params.resolvedProject.orgId,
1126
projectId: params.resolvedProject.projectId,
1127
}).pipe(
1136
projectScope: toolkitProjectScope(params.resolvedProject),
1137
})
1138
)
1284
- )));
1139
+ );
1140
if (definition) {
1141
yield* validateToolInputArgumentsWithDefinition(
1142
params.slug,
1185
}
1186
1187
yield* perfDebugLog('execute.tool_call.start', { slug: params.slug });
1333
- const result = yield* params.executor.execute(params.slug, params.executeParams).pipe(
1334
- Effect.raceFirst(validationGuard),
1188
+ const validateArgs = verificationDisabled
1189
+ ? Effect.void
1190
+ : validateToolInputBeforeExecute({
1191
+ slug: params.slug,
1192
+ args: params.args,
1193
+ resolvedProject: params.resolvedProject,
1194
+ });
1195
+ const result = yield* validateArgs.pipe(
1196
+ Effect.andThen(params.executor.execute(params.slug, params.executeParams)),
1197
Effect.matchEffect({
1198
onFailure: error =>
1199
Effect.gen(function* () {
1202
slug: params.slug,
1203
successful: false,
1204
});
1343
- yield* invalidateToolInputDefinition(params.slug).pipe(
1344
- Effect.catch(() => Effect.void)
1345
- );
1205
+ // The validation error points the user at the cached schema, so
1206
+ // it has to stay on disk.
1207
+ if (!(error instanceof ToolInputValidationError)) {
1208
+ yield* invalidateToolInputDefinition(params.slug).pipe(
1209
+ Effect.catch(() => Effect.void)
1210
+ );
1211
+ }
1212
yield* spinner.error();
1213
const summary = yield* handleExecutionError(params.ui, error, {
1214
toolSlug: params.slug,
1249
}),
1250
})
1251
);
1386
- if (validationState.awaitCachedValidationDecision) {
1387
- const decision = yield* validationState.awaitCachedValidationDecision;
1388
- if (decision.status === 'fail') {
1389
- yield* perfDebugLog('execute.validation.post_success_failure_ignored', {
1390
- slug: params.slug,
1391
- });
1392
- }
1393
- }
1394
-
1252
if (!result.successful) {
1253
yield* invalidateToolInputDefinition(params.slug).pipe(Effect.catch(() => Effect.void));
1254
const logId = result.logId